0

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?

4
  • 3
    You can do one thing. Before preparing JSON object. You can check for a dummy JSON by serializing it on the server side and keeping a debugger. Commented Aug 5, 2013 at 7:58
  • before Deserialize, did you try to serialize and see if the JSON string you are using is same as it generate, I think there is extra { } going in ... not sure though Commented Aug 5, 2013 at 8:00
  • Simply try var jsSerialize = new JavaScriptSerializer(); var cities = jsSerialize.Serialize(new Cities()); and keep Debugger on the next statement Commented Aug 5, 2013 at 8:00
  • Note there is a case difference between city, cities and City, Cities. Commented Aug 5, 2013 at 8:00

1 Answer 1

8

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#

Sign up to request clarification or add additional context in comments.

7 Comments

Invalid JSON primitive: cities.
@RoyiNamir: you shoud wrap the whole jscon into a pair of brackets. I update my code to reflect this.
HOwever please notice that { id: 1, name: "A.S.Peta", status: "Active" } is not a valid json. it's just that the JSS tolerate it.
@RoyiNamir: Why is that JSON object invalid?
@stakx try it yourself jsonlint.com. each object key should come under ". i.sstatic.net/lzhFy.jpg
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.