简体   繁体   中英

JSON Parse in C#

What is wrong with this code?

JSON

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

C# Code

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);

Not populating internal object City. but showing collection with all records. Any Idea?

The "inner" city in your json object is adding a nested object within the array.

Try this json code :

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

If you need to stick to your originial json structure, you can try this c# code:

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; }
}

This code has been automatically generated by this very useful web tool: json2C#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM