简体   繁体   中英

How can I parse a JSON string to .Net object using Json.Net?

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"
    } ]
    }
]

Your JSON isn't actually JSON - you need commas after the fields:

[
    {
    id: "new01",
    name: "abc news",
    icon: "",
    channels: [
    {
    id: 1001,
       ....

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:

    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; }
    }

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:

    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; }
    }

Once you've done this, you can parse a string containing your JSON like this:

var result = JsonConvert.DeserializeObject<List<MainItem>>(inputString);

yup, it's JsonConvert.DeserializeObject(json string)

try using JsonConvert.SerializeObject(object) to create the JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM