Search code examples
c#javascriptserializer

c# JavaScriptSerializer on JSON containing string + dictionary


May i know how to parsing the JSON stated as below..... the JSON is part of Yahoo OAuth Contacts list.

JSON:

"fields":[{                 
                "id":2,
                "type":"nickname",
                "value":"Hello"
            },
            {
                "id":3,
                "type":"email",
                "value":"MyTesting@hotmail.com"
            },
            {       
                "id":1,
                "type":"name",
                "value":{
                    "givenName":"Otopass",  
                    "middleName":"Test",
                    "familyName":"Hotmail"
                    },
            }],

C# object :

    private class fields 
    {
        public string id { get; set; }
        public string type { get; set; }
        //public string value { get; set; }                        //Stuck At Here !!!!
        //public Dictionary<string, string> value { get; set; }    //Stuck At Here !!!!
    }  

How to parse the "value"?? since it's combination type of String & Dictionary.


Solution

  • I can't answer it using JavaScriptSerializer but you can do it using json.Net and Linq

    var jObj = JObject.Parse(json);
    var fields = jObj["fields"]
                    .Select(x => new Field
                    {
                        Id = (int)x["id"],
                        Type = (string)x["type"],
                        Value = x["value"] is JValue 
                                ? new Dictionary<string,string>(){{"",(string)x["value"]}}
                                : x["value"].Children()
                                            .Cast<JProperty>()
                                            .ToDictionary(p => p.Name, p => (string)p.Value)
                    })
                    .ToList();
    
    
    private class Field
    {
        public int Id { get; set; }
        public string Type { get; set; }
        public Dictionary<string, string> Value { get; set; }    
    } 
    

    PS: I fixed your partial json string as

    string json = 
    @"{""fields"":[
        {                 
            ""id"":2,
            ""type"":""nickname"",
            ""value"":""Hello""
        },
        {
            ""id"":3,
            ""type"":""email"",
            ""value"":""MyTesting@hotmail.com""
        },
        {       
            ""id"":1,
            ""type"":""name"",
            ""value"":{
                ""givenName"":""Otopass"",  
                ""middleName"":""Test"",
                ""familyName"":""Hotmail""
                }
        }
    ]}";