1

I'm using JSON.NET in .NET 4.0. i receive a json string and try to put it in the class. but an exception happens and i cant solve it. here is my json string:

{
  "Records": [
    {
      "TransID": "902473653",
      "Date": "6/12/2015 10:47:00 AM",
      "ProductID": "90",
      "ItemDes": "test",
      "Amount": "20000",
      "BankTransactionID": "FM60aW33EavtDcYmXbz5vy/UvUAiQF",
      "Banktype": "IPG_SAMAN"
    },
    {
      "TransID": "910920749",
      "Date": "6/11/2015 11:05:00 AM",
      "ProductID": "91",
      "ItemDes": "test",
      "Amount": "20000",
      "BankTransactionID": "mAdWPNY++QdcKYepuIvuC4+UdZnQAa",
      "Banktype": "IPG_SAMAN"
    },
    {
      "TransID": "81131964",
      "Date": "11/24/2014 9:08:00 AM",
      "ProductID": "81",
      "ItemDes": "test",
      "Amount": "90000",
      "BankTransactionID": "123456789012",
      "Banktype": "USSD_InfoTech"
    }
  ]
}

my classes:

class Record
{
    public string TransID;
    public DateTime Date;
    public string ProductID;
    public string ItemDes;
    public string Amount;
    public string BankTransactionID;
    public string Banktype;
}
class Records
{
    public List<Record> data {get;set;}
}

my Deserializer code:

Records record;
record = new JavaScriptSerializer().Deserialize<Records>(result);
foreach (var item in record.data)
{
    textBox1.Text = item.TransID;
    textBox2.Text = item.Date.ToString();
    textBox3.Text = item.ProductID;
    textBox4.Text = item.Amount;
}

but it looks like record is null because null exceptions happen in foreach loop.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321

2 Answers2

3

Your List<Record> property needs to be properly named. It should be "Records":

public class RootObject
{
    public List<Record> Records { get; set; }
}

This means you'll need to change the class name. In my example, it's called RootObject.

Or, you could annotate with the JsonProperty attribute:

public class Records
{
    [JsonProperty("Records")]
    public List<Record> Data { get; set; }
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
0

You can use JsonProperty to change the name of the field. Please see this answer for more details: https://stackoverflow.com/a/15916121/686001

Community
  • 1
  • 1
Tibi
  • 1,507
  • 1
  • 9
  • 10