[英]Newtonsoft.JSON serialization results in a sole string with the object's type
[英]JSON string serialization (Newtonsoft.JSON)
我得到一个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:
位? 如果是这样,则需要将其删除(删除第一个{
字符之前的字符串中的所有内容),然后它应该对您有用。
这里有一些问题:
您的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}
并显示数据已成功反序列化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.