-1

我可以知道如何解析如下所述的 JSON ...... JSON 是 Yahoo OAuth 联系人列表的一部分。

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# 对象:

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

如何解析“价值”?因为它是字符串和字典的组合类型。

4

1 回答 1

0

我无法使用 JavaScriptSerializer 回答它,但您可以使用json.Net和 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:我将您的部分 json 字符串固定为

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""
            }
    }
]}";
于 2013-06-04T17:34:50.743 回答