c# 如何将Json数据转换为对象
我正在尝试使用 Newtonsoft.Json 库解析一些 JSON。该文档似乎有点稀疏,我对如何完成我需要的内容感到困惑。这是我需要解析的 JSON 格式。
const string json = @"{ ""error"" : ""0"",
""result"" :
{
""1256"" : {
""data"" : ""type any data"",
""size"" : ""12345""
},
""1674"" : {
""data"" : ""type any data"",
""size"" : ""12345""
},
// ... max - 50 items
}
}";
我正在尝试将 JSON 数据转换为某种不错的对象。这是我的课程:
public class ListLink
{
public String data{ get; set; }
public String size { get; set; }
}
public class SubResult
{
public ListLink attributes { get; set; }
}
public class Foo
{
public Foo() { results = new List<SubResult>(); }
public String error { get; set; }
public List<SubResult> results { get; set; }
}
.....
List<Foo> deserializedResponse =
(List<Foo>)Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(List<Foo>));
但我总是收到错误。有什么想法吗?
编辑: 我收到错误:
Newtonsoft.Json.JsonSerializationException: Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[ConsoleApplication1.Foo]' (...)
I'm trying to parse some JSON using the Newtonsoft.Json library. The documentation seems a little sparse and I'm confused as to how to accomplish what I need. Here is the format for the JSON I need to parse through.
const string json = @"{ ""error"" : ""0"",
""result"" :
{
""1256"" : {
""data"" : ""type any data"",
""size"" : ""12345""
},
""1674"" : {
""data"" : ""type any data"",
""size"" : ""12345""
},
// ... max - 50 items
}
}";
I'm trying to convert JSON data a nice object of some kind. Here is my class:
public class ListLink
{
public String data{ get; set; }
public String size { get; set; }
}
public class SubResult
{
public ListLink attributes { get; set; }
}
public class Foo
{
public Foo() { results = new List<SubResult>(); }
public String error { get; set; }
public List<SubResult> results { get; set; }
}
.....
List<Foo> deserializedResponse =
(List<Foo>)Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(List<Foo>));
But i always get an error. Any ideas?
EDIT:
I get an Error:
Newtonsoft.Json.JsonSerializationException: Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[ConsoleApplication1.Foo]' (...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这有点难看,但可能适合您的需求。它也不使用第三方解决方案。抱歉,如果有点混乱!
This is a bit ugly, but may suit your needs. It doesn't use a third party solution either. Apologies if it is a bit kludgey!!
示例:
输出:
Sample:
OUTPUT: