如何使用Json.Net将JSON字符串解析为.Net对象?
问题描述:
我想分析的字符串:如何使用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"
} ]
}
]
答
您的JSON是不实际的JSON - 你需要逗号域之后:
[
{
id: "new01",
name: "abc news",
icon: "",
channels: [
{
id: 1001,
....
假设你已经做了和正在使用JSON.NET ,那么您将需要类来表示每个元素 - 主数组中的主要元素以及子“Channel”元素。
喜欢的东西:
public class Channel
{
public int Id { get; set; }
public string Name { get; set; }
public string SortKey { get; set; }
public string SourceId { get; set; }
}
public class MainItem
{
public string Id { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public List<Channel> Channels { get; set; }
}
由于存在C#成员命名约定和JSON名之间不匹配,则需要每个成员装饰用的映射告诉JSON解析器什么JSON领域被称为:
public class Channel
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("sortkey")]
public string SortKey { get; set; }
[JsonProperty("sourceid")]
public string SourceId { get; set; }
}
public class MainItem
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("icon")]
public string Icon { get; set; }
[JsonProperty("channels")]
public List<Channel> Channels { get; set; }
}
一旦你做到了这一点,你可以分析包含字符串您的JSON是这样的:
var result = JsonConvert.DeserializeObject<List<MainItem>>(inputString);
+0
谢谢,我会试试你的方式并通知结果。谢谢达米安。 – Thanh 2011-05-09 10:12:14
答
是的,它是JsonConvert.DeserializeObject(json字符串)
尝试使用JsonConvert.SerializeObject(object)来创建JSON。
我曾尝试读取所有文档,但未成功:D – Thanh 2011-05-09 04:40:47
要创建一个对象或JsonObject? – Phill 2011-05-09 05:53:20