1

I'm trying to deserialize an array using Newtonsoft so I can display the list of values but I keep getting this error no matter what I try: Exception thrown: 'System.NullReferenceException'

This is my JSON:

[
  {
    "M": {
      "ItemNo": {
        "S": "111803"
      },
      "Name": {
        "S": "Viper HD 10 x 50 RP Bi"
      },
      "Price": {
        "N": "549.99"
      },
      "Quantity": {
        "N": "1"
      }
    }
  },
  {
    "M": {
      "ItemNo": {
        "S": "111715"
      },
      "Name": {
        "S": "Cantilever / 2\" Of"
      },
      "Price": {
        "N": "89.99"
      },
      "Quantity": {
        "N": "1"
      }
    }
  }
]

This is my C# class:

public class ItemNo
{

    [JsonProperty("S")]
    public string S { get; set; }
}

public class Name
{

    [JsonProperty("S")]
    public string S { get; set; }
}

public class Price
{

    [JsonProperty("N")]
    public string N { get; set; }
}

public class Quantity
{

    [JsonProperty("N")]
    public string N { get; set; }
}

public class M
{

    [JsonProperty("ItemNo")]
    public ItemNo ItemNo { get; set; }

    [JsonProperty("Name")]
    public Name Name { get; set; }

    [JsonProperty("Price")]
    public Price Price { get; set; }

    [JsonProperty("Quantity")]
    public Quantity Quantity { get; set; }
}

public class Items
{

    [JsonProperty("M")]
    public M M { get; set; }
}

And my code to deserialize and display the first array item values but getting null reference error:

List<M> mItems = JsonConvert.DeserializeObject<List<M>>(itemsJson);
Console.WriteLine("Items Line Count: " + mItems.Count);
Console.WriteLine("Items#: " + mItems[0].ItemNo.S);
Console.WriteLine("ItemsNam: " + mItems[1].ItemName.S);
Console.WriteLine("ItemsPrc: " + mItems[3].Price.N);

1 Answer 1

1

You have two issues in the code :

1 - Json should be deserialized to List<Items> not List<M>
2 - mItems[3] will gives you an exception, because the collection contains just two elements.

Change the code to :

List<Items> mItems = JsonConvert.DeserializeObject<List<Items>>(json1);
Console.WriteLine("Items Line Count: " + mItems.Count);

foreach(Items item in mItems)
{
    Console.WriteLine($"No :{item.M.ItemNo.S}, Name :{item.M.Name.S}, Price :{item.M.Price.N}, Quantity :{item.M.Quantity.N}");
}

Result

Items Line Count: 2
No :111803, Name :Viper HD 10 x 50 RP Bi, Price :549.99, Quantity :1
No :111715, Name :Cantilever / 2" Of,     Price :89.99,  Quantity :1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.