json字符串到c#对象

时间:2015-10-18 10:31:46

标签: c# json json.net

我试图将这个json字符串反序列化为c#对象,但我没有成功。一个人帮助我如何实现这一点。

    {
    products_info: [10]
    0:  {
    product_id: "20"
    product_name: "Crocin"
    medical_name: "Crocin"
    slot_no: "1"
    num_of_units: "10"
    price: "16"
    expiry_date: "2016-01-15"
    product_image: "http://xyz/prdct_imgs/eno.png"
    }-

    ..................

    9:  {
    product_id: "29"
    product_name: "Stayfree"
    medical_name: "Stayfree"
    slot_no: "11"
    num_of_units: "10"
    price: "30"
    expiry_date: "2016-09-02"
    product_image: "http://xyz/prdct_imgs/eno.png"
    }-
    -
    response: "1"
    }

1 个答案:

答案 0 :(得分:2)

您提供的Json似乎格式错误(请查看JSON格式的规则),以下是它的外观:

{
    "products_info": [
        {
            "product_id": "20",
            "product_name": "Crocin",
            "medical_name": "Crocin",
            "slot_no": "1",
            "num_of_units": "10",
            "price": "16",
            "expiry_date": "2016-01-15",
            "product_image": "http://xyz/prdct_imgs/eno.png"
        },
        {
            "product_id": "29",
            "product_name": "Stayfree",
            "medical_name": "Stayfree",
            "slot_no": "11",
            "num_of_units": "10",
            "price": "30",
            "expiry_date": "2016-09-02",
            "product_image": "http://xyz/prdct_imgs/eno.png"
        }
    ],
    "response": "1"
}

现在,当您使用正确的格式时,您可以使用Json.net进行反序列化(例如,您可以从nuget安装它)到以下类:

public class ProductsInfo
{
    public string product_id { get; set; }
    public string product_name { get; set; }
    public string medical_name { get; set; }
    public string slot_no { get; set; }
    public string num_of_units { get; set; }
    public string price { get; set; }
    public string expiry_date { get; set; }
    public string product_image { get; set; }
}

public class YourClass
{
    public List<ProductsInfo> products_info { get; set; }
    public string response { get; set; }
}

YourClass yourClass = JsonConvert.DeserializeObject(json);

你可以在这里看到它是如何完成的: http://www.newtonsoft.com/json/help/html/deserializeobject.htm