我得到一个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"保持为空。我哪里错了,为什么?它正在编译,没有任何例外。
这里有几个问题:
-
您的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 }] }}
-
您正在尝试反序列化
Response
类,但该类中没有字段response
,它显然是某个包含类中的字段。因此,您需要提取出实际的Response
。 -
Item
中的属性aid
需要命名为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));
}
这会产生调试输出
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}
并显示数据已成功反序列化。
您的代码对我来说是按原样工作的。您收到的JSON字符串开头是否包含response:
位?如果是这样,您需要去掉它(删除第一个{
字符之前字符串中的所有内容),那么它应该对您有效。