C#中的JSON解析

时间:2013-08-05 07:56:38

标签: c# json

此代码有什么问题?

JSON

cities: [
{
    city: {
        id: 1,
        name: "A.S.Peta",
        status: "Active"
    }
},..............

C#代码

public class Cities
{
    public City[] cities;    
}

public class City
{
    public int id; //{ get; set; }
    public string name; //{ get; set; }
    public string status; //{ get; set; }
}

//De-Serialization
var jsSerialize = new JavaScriptSerializer();
var cities = jsSerialize.Deserialize<Cities>(result);

不填充内部对象City。但显示所有记录的集合。有什么想法吗?

1 个答案:

答案 0 :(得分:8)

json对象中的“内部”city是在数组中添加嵌套对象。

试试这个json代码:

{
    "cities": [
    {  
        "id": 1,
        "name": "A.S.Peta",
        "status": "Active"
    },
    {  
        "id": 2,
        "name": "Strasbourg",
        "status": "Active"
    }
    ]
}

如果您需要坚持原始的json结构,可以试试这个c#代码:

public class City2
{
    public int id { get; set; }
    public string name { get; set; }
    public string status { get; set; }
}

public class City
{
    public City2 city { get; set; }
}

public class RootObject
{
    public List<City> cities { get; set; }
}

此代码已由此非常有用的网络工具自动生成:json2C#