我的免费托管网站上的php上传有JSON响应,会输出以下内容:
{"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"}]}
我有这个C#表单来测试我是否正确地反序列化它:
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);
}
}
richTextBox1.Text = getResponse.ToString();
部分的一切都很好。它是测试我是否正确得到响应。但当它进入foreach部分时,它会崩溃并产生NullReferenceException
。 listView1.Items.Add
部分只是为了测试它是否被反序列化。我将为foreach部分做的是将每一行上传到我的数据库中。