0

I have a JSON response from my php upload in a free hosting site that will output the following:

{"cart":[{"cardno":"1111111111","product_id":"10000104","name":"Hotsilog","quantity":"1","price":"35","category":"breakfast"},{"cardno":"1111111111","product_id":"10000107","name":"Champorado","quantity":"1","price":"15","category":"breakfast"}]}

and I have this C# form to test if im deserializing it properly:

public class Costing
{
    public List<CustomerCosting> costing { get; set; }
}

public class CustomerCosting
{
    public string id { get; set; }
    public string cardno { get; set; }
    public string product_id { get; set; }
    public string name { get; set; }
    public string quantity { get; set; }
    public string price { get; set; }
    public string category { get; set; }
}

private void button3_Click(object sender, EventArgs e)
{
    NameValueCollection userInfo = new NameValueCollection();
    userInfo.Add("cardno", textBox6.Text);
    byte[] uploadVal = client.UploadValues("http://eallowance.x10host.com/v1/getCart.php", "POST", userInfo);
    string getResponse = Encoding.ASCII.GetString(uploadVal);

    richTextBox1.Text = getResponse.ToString();
    Costing customerCosting = JsonConvert.DeserializeObject<Costing>(getResponse);

    foreach (var item in customerCosting.costing)
    {
        listView1.Items.Add("name: {3}", item.name);
    }
}

Everything is good up to the richTextBox1.Text = getResponse.ToString(); part. It is there to test if im getting the response properly. But when it enters the foreach part, it crash and gives a NullReferenceException. The listView1.Items.Add part is just to test if it got deserialized. What I will do for the foreach part is to upload each row into my database.

poke
  • 307,619
  • 61
  • 472
  • 533
Ryan Rems
  • 1
  • 1
  • Well, is it null? – rndus2r Sep 29 '17 at 08:15
  • Use http://json2csharp.com/ to correct your model. In the JSON the root object's only property is named `"cart"` not `"costing"`. – dbc Sep 29 '17 at 08:17
  • i think so, no items is added in listView – Ryan Rems Sep 29 '17 at 08:17
  • The name of the property in the JSON that contains the list is `cart` not `costing` as you attempt to use in your `Costing` type. Change the property to `public List cart { get; set; }` and it will work. – poke Sep 29 '17 at 08:24
  • I think that `customerCosting` object is null and you are trying to access a property on a null object. Always precheck an object before using. Also, your serialized content has `cart` and deserializer has no information about it and was not able to build\deserialize `Costing` object. Provide a mapping or an annotation for the same. I'll also suggest that Create Costing object and serialize it to see how Costing gets serialized. – Sunil Singhal Sep 29 '17 at 14:43

0 Answers0