反序列化GET响应

时间:2012-12-10 18:22:33

标签: c# json

如何反序列化此文本。我尝试使用JSON,但我收到“无效的JSON原语”错误。

{
"meta": {
  "limit": 20,
  "next": null,
  "offset": 0,
  "previous": null,
  "total_count": 1
},
"objects": [
  {
     "blocked": false,
     "groups": [],
     "id": "1111",
     "name": "John Doe",
     "number": "+15555555555",
     "resource_uri": "/api/v1/contacts/1111/"
  }
 ]
}

这是我使用的代码:

var jss = new JavaScriptSerializer();
var dictionary = jss.Deserialize<Dictionary<string, string>>(buffer.ToString());

1 个答案:

答案 0 :(得分:1)

易于修复。反序列化为<Dictionary<string, object>而不是<Dictionary<string, string>

var dictionary = jss.Deserialize<Dictionary<string, object>>(buffer.ToString());

完整的测试代码

string json = @"{
    ""meta"": {
        ""limit"": 20,
        ""next"": null,
        ""offset"": 0,
        ""previous"": null,
        ""total_count"": 1
    },
    ""objects"": [
        {
            ""blocked"": false,
            ""groups"": [],
            ""id"": ""1111"",
            ""name"": ""John Doe"",
            ""number"": ""+15555555555"",
            ""resource_uri"": ""/api/v1/contacts/1111/""
        }
        ]
    }";

var jss = new JavaScriptSerializer();
var dictionary = jss.Deserialize<Dictionary<string, object>>(json);