9

I just started dabbling with C#, and I've been banging my head over JSON deserialization for a while now. I'm using Newtonsoft.Json library. I'm expecting just a json response of an array of dictionaries as such

[{"id":"669","content":" testing","comments":"","ups":"0","downs":"0"}, {"id":"482","content":" test2","comments":"","ups":"0","downs":"0"}]

Right now I have: (note: download is just a string holding the json string)

string[] arr = JsonConvert.DeserializeObject<string[]>(download);

I've tried many different ways of doing this, each failed. Is there a standard way for parsing json of this type?

Chris
  • 7,270
  • 19
  • 66
  • 110
  • Possible duplicate of http://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net – Sumo Feb 01 '13 at 05:03

2 Answers2

23

You have an array of objects not strings. Create a class that maps the properties and deserialize into that,

public class MyClass {
    public string id { get; set; }
    public string content { get; set; }
    public string ups { get; set; }
    public string downs { get; set; }
}

MyClass[] result = JsonConvert.DeserializeObject<MyClass[]>(download);

There are only a few basic types in JSON, but it is helpful to learn and recognize them. Objects, Arrays, strings, etc. http://www.json.org/ and http://www.w3schools.com/json/default.asp are good resources to get started. For example a string array in JSON would look like,

["One", "Two", "Three"]
Despertar
  • 21,627
  • 11
  • 81
  • 79
  • 2
    You're welcome! In addition to serializing into a strongly typed class, you can use `JObject.Parse(jsonstring)`. This returns a JObject which you can then access the properties of like `obj.Value("content")`. Of course the strongly typed approach is recommend, but it's good to know the alternatives :) – Despertar Feb 01 '13 at 06:09
  • @Despertar What does (download) exacly stand for? – Fernando S. Kroes Feb 04 '16 at 10:43
  • @Fernando This was the variable Chris was using, it holds the json string that needs to be parsed. – Despertar Feb 04 '16 at 18:40
1

I implement this and hope this is helpful all.

 var jsonResponse = 
  [{"Id":2,"Name":"Watch"},{"Id":3,"Name":"TV"},{"Id":4,"Name":""}]

 var items = JsonConvert.DeserializeObject<List<MyClass>>(jsonResponse);

where MyClass is the entity

 public class MyClass
            {
                public int Id { get; set; }
                public string Name { get; set; }
            }
Rahul
  • 11
  • 3