【问题标题】:How do I deserialise this JSON?如何反序列化 JSON?
【发布时间】:2015-05-19 08:04:08
【问题描述】:

我之前没有对 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”的字符串,例如,我将如何存储该查询然后检索项目名称?

【问题讨论】:

  • 它编译...但我不知道我如何找到这些信息?我尝试只在 msgbox 中显示项目名称,但我放在那里的任何内容似乎都没有问题? =/
  • “查找该信息”是什么意思?我已在我的答案中添加了如何在消息框中显示名称。
  • 刚刚评论了答案,智能感知没有出现在 VS 中。 >.

标签: c# json json.net


【解决方案1】:

用途:

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

根据您提供的代码,我刚刚测试成功。

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

MessageBox.Show(deserialized.item.name);

【讨论】:

  • 哦,>.
猜你喜欢
  • 1970-01-01
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多