如何使用 Json.Net 将 JSON 字符串解析为 .Net 对象?
我要解析的字符串:
[
{
id: "new01"
name: "abc news"
icon: ""
channels: [
{
id: 1001
name: "News"
url: "http://example.com/index.rss"
sortKey: "A"
sourceId: "1"
},
{
id: 1002
name: "abc"
url: "http://example.com/android.rss"
sortKey: "A"
sourceId: "2"
} ]
},
{
id: "new02"
name: "abc news2"
icon: ""
channels: [
{
id: 1001
name: "News"
url: "http://example.com/index.rss"
sortKey: "A"
sourceId: "1"
},
{
id: 1002
name: "abc"
url: "http://example.com/android.rss"
sortKey: "A"
sourceId: "2"
} ]
}
]
The string I want to parse:
[
{
id: "new01"
name: "abc news"
icon: ""
channels: [
{
id: 1001
name: "News"
url: "http://example.com/index.rss"
sortKey: "A"
sourceId: "1"
},
{
id: 1002
name: "abc"
url: "http://example.com/android.rss"
sortKey: "A"
sourceId: "2"
} ]
},
{
id: "new02"
name: "abc news2"
icon: ""
channels: [
{
id: 1001
name: "News"
url: "http://example.com/index.rss"
sortKey: "A"
sourceId: "1"
},
{
id: 1002
name: "abc"
url: "http://example.com/android.rss"
sortKey: "A"
sourceId: "2"
} ]
}
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 JSON 实际上不是 JSON - 您需要在字段后添加逗号:
假设您已完成此操作并且正在使用 JSON.NET,那么您需要类来表示每个元素 - 主数组中的主要元素以及子“Channel”元素。
类似于:
因为 C# 成员命名约定和 JSON 名称之间不匹配,所以您需要使用映射来装饰每个成员,以告诉 JSON 解析器 json 字段的名称:
完成此操作后,您可以像这样解析包含 JSON 的字符串:
Your JSON isn't actually JSON - you need commas after the fields:
Assuming you've done that and that you are using JSON.NET, then you'll need classes to represent each of the elements - the main elements in the main array, and the child "Channel" elements.
Something like:
Because there is a mismatch between the C# member naming conventions and the JSON names, you'll need to decorate each member with a mapping to tell the JSON parser what the json fields are called:
Once you've done this, you can parse a string containing your JSON like this:
是的,它是 JsonConvert.DeserializeObject(json string)
尝试使用 JsonConvert.SerializeObject(object) 创建 JSON。
yup, it's JsonConvert.DeserializeObject(json string)
try using JsonConvert.SerializeObject(object) to create the JSON.