JSON字符串序列化(Newtonsoft.JSON)

时间:2014-11-11 19:03:00

标签: c# json json.net

我获得了一个JSON字符串作为HTTP响应。这个字符串看起来像:

response: {
    count: 524,
    items: [{
        id: 318936948,
        owner_id: 34,
        artist: 'The Smiths',
        title: 'How Soon Is Now',
        duration: 233,
        url: 'link',
        genre_id: 9
    }, {
        id: 312975563,
        owner_id: 34,
        artist: 'Thom Yorke',
        title: 'Guess Again!',
        duration: 263,
        url: 'link',
        genre_id: 22
    }]
}

我有Newtonsoft.Json库,还有Response和Item:

[JsonObject(MemberSerialization.OptIn)]
class Response
{
    [JsonProperty("count")]
    public int count { get; set; }
    [JsonProperty("items")]
    public List<Item> items { get; set; }
}
[JsonObject(MemberSerialization.OptOut)]
class Item
{
    public string aid { get; set; }
    public string owner_id { get; set; }
    public string artist { get; set; }
    public string title { get; set; }
    public string duration { get; set; }
    public string url { get; set; }
    public int lyrics_id { get; set; }
    public int album_id { get; set; }
    public int genre_id { get; set; }
}

我反复将其反序列化:

Response r = JsonConvert.DeserializeObject<Response>(line);

它不起作用,“r”仍为空。我哪里错了,为什么?它正在编译,没有例外。

2 个答案:

答案 0 :(得分:0)

您的代码按原样运行。您收到的JSON字符串是否在开头包含response:位?如果是这样,你需要将其删除(在第一个{字符之前删除字符串中的所有内容),然后它应该适合你。

答案 1 :(得分:0)

这里有一些问题:

  1. 您的JSON字符串缺少外括号。它应该看起来像

    { response: {
        count: 524,
        items: [{
            id: 318936948,
            owner_id: 34,
            artist: 'The Smiths',
            title: 'How Soon Is Now',
            duration: 233,
            url: 'link',
            genre_id: 9
        }, {
            id: 312975563,
            owner_id: 34,
            artist: 'Thom Yorke',
            title: 'Guess Again!',
            duration: 263,
            url: 'link',
            genre_id: 22
        }]
    }}
    
  2. 您正在尝试反序列化Response类,但此类中没有字段response,它显然是某个包含类的字段。因此,您需要提取实际的Response

  3. aidItem的财产id需要命名为 // Fix missing outer parenthesis var fixedLine = "{" + line + "}"; // Parse into a JObject var mapping = JObject.Parse(fixedLine); // Extract the "response" and deserialize it. Response r = mapping["response"].ToObject<Response>(); Debug.WriteLine(r.count); foreach (var item in r.items) { Debug.WriteLine(" " + JsonConvert.SerializeObject(item)); }

  4. 所以,以下似乎有效:

    524
      {"id":"318936948","owner_id":"34","artist":"The Smiths","title":"How Soon Is Now","duration":"233","url":"link","lyrics_id":0,"album_id":0,"genre_id":9}
      {"id":"312975563","owner_id":"34","artist":"Thom Yorke","title":"Guess Again!","duration":"263","url":"link","lyrics_id":0,"album_id":0,"genre_id":22}
    

    这会产生调试输出

    {{1}}

    并显示数据已成功反序列化。