如何反序列化JSON?

时间:2015-03-17 01:27:43

标签: c# json json.net

我之前没有用JSON做过任何事......所以我可能只是错过了一步。

以下是我想要反序列化的JSON示例:

{"item":{"icon":"http://services.runescape.com/m=itemdb_rs/4765_obj_sprite.gif?id=4798","icon_large":"http://services.runescape.com/m=itemdb_rs/4765_obj_big.gif?id=4798","id":4798,"type":"Ammo","typeIcon":"http://www.runescape.com/img/categories/Ammo","name":"Adamant brutal","description":"Blunt adamantite arrow...ouch","current":{"trend":"neutral","price":237},"today":{"trend":"neutral","price":0},"members":"true","day30":{"trend":"positive","change":"+1.0%"},"day90":{"trend":"negative","change":"-0.0%"},"day180":{"trend":"positive","change":"+0.0%"}}}

我把它放入" Json 2 C#"并最终创建了这个新的.cs文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RSTool.Models
{

    public class Current
    {
        public string trend { get; set; }
        public int price { get; set; }
    }

    public class Today
    {
        public string trend { get; set; }
        public int price { get; set; }
    }

    public class Day30
    {
        public string trend { get; set; }
        public string change { get; set; }
    }

    public class Day90
    {
        public string trend { get; set; }
        public string change { get; set; }
    }

    public class Day180
    {
        public string trend { get; set; }
        public string change { get; set; }
    }

    public class Item
    {
        public string icon { get; set; }
        public string icon_large { get; set; }
        public int id { get; set; }
        public string type { get; set; }
        public string typeIcon { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public Current current { get; set; }
        public Today today { get; set; }
        public string members { get; set; }
        public Day30 day30 { get; set; }
        public Day90 day90 { get; set; }
        public Day180 day180 { get; set; }
    }

    public class RootObject
    {
        public Item item { get; set; }
    }
}

所以,我有课。我可以从它的位置检索JSON作为字符串,但我真的不知道如何反序列化它...我已经安装了Newtonsoft.Json并尝试使用PopulateObject和Deserializer但没有运气......

假设我的JSON存储为名为" json"的字符串,我该如何存储该查询然后检索项目名称?

1 个答案:

答案 0 :(得分:1)

使用:

var deserialized = JsonConvert.DeserializeObject<RootObject>(json);

我根据您提供的代码成功测试了这个。

然后,您可以正常访问对象的属性:

MessageBox.Show(deserialized.item.name);