Search code examples
c#.netjson.netjson-deserialization

How do I deserialize a Json object?


This is the code I use to deserialize JSON.But when I try writing it in console, it says "System.Collections.Generic.Dictionary`2[System.String, System.Object]"

System.Net.WebClient wc = new System.Net.WebClient();
string Jayson = wc.DownloadString("http://api.urbandictionary.com/v0/define?term=api");
object obj = JsonHelper.Deserialize(Jayson);
Dictionary<string, object> values = 
        JsonConvert.DeserializeObject<Dictionary<string, object>>(Jayson);
Console.WriteLine(values);

How do I deserialize it and extract only the "definition" from the JSON?


Solution

  • You can create some concrete types to map to and deserialize using those rather than more generic types, for example:

    public class Result
    {
    
        [JsonProperty("definition")]
        public string Definition { get; set; }
    
        [JsonProperty("author")]
        public string Author { get; set; }
    
        [JsonProperty("permalink")]
        public string PermaLink { get; set; }
    
    }
    
    public class Results
    {
    
        [JsonProperty("list")]
        public List<Result> List { get; set; }
    
        [JsonProperty("tags")]
        public List<string> Tags { get; set; }
    
    }
    

    Then:

    var results = JsonConvert.DeserializeObject<Results>(json);
    

    You can then iterate the definitions:

    foreach(var result in results.List)
        Console.WriteLine(result.Definition);
    

    Json.NET will ignore the other properties it can't map so you can add/remove them as needed.