反序列化 .json 字符串返回:'Object reference not set to an instance of an object'



我正在尝试读取.json响应。我在这里粘贴了回应:https://pastebin.com/0zgg39si

然后我使用以下代码。运行代码时,我会收到以下错误:

" var deserializedTickers"

system.nullReferenceException:'对象引用未设置为对象的实例。'

代码为以下。我不确定是什么原因造成的?

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
        public void test()
        {
            //responseBody holds the .json response
            String responseBody = "";
            var deserializedTickers = JsonConvert.DeserializeObject<TickersRoot>(responseBody);
            foreach (var ticker in deserializedTickers.Tickers)
            {
                var symbol2 = ticker.Value.Symbol;
            }
        }
        public class TickersRoot { public Dictionary<string, Ticker> Tickers { get; set; } }
        public class Ticker
        {
            public string Symbol { get; set; }
            public long Timestamp { get; set; }
            public DateTime Datetime { get; set; }
            public double High { get; set; }
            public double Low { get; set; }
            public double Bid { get; set; }
            public double Ask { get; set; }
            public double Vwap { get; set; }
            public double Open { get; set; }
            public double Close { get; set; }
            public double Last { get; set; }
            public double BaseVolume { get; set; }
            public double QuoteVolume { get; set; }
            public Info Info { get; set; }
        }
        public class Info
        {
            public List<string> a { get; set; }
            public List<string> b { get; set; }
            public List<string> c { get; set; }
            public List<string> v { get; set; }
            public List<string> p { get; set; }
            public List<int> t { get; set; }
            public List<string> l { get; set; }
            public List<string> h { get; set; }
            public string o { get; set; }
        }

基于响应,您的信息类应该是这样的(设置数据类型以符合您的需求):

public class Info
{
    public string Buy { get; set; }
    public string Sell { get; set; }
    public string Open { get; set; }
    public string Low { get; set; }
    public string High { get; set; }
    public string Last { get; set; }
    public string Vol { get; set; }
}

由于您没有JSON主体上称为" tickers"的属性,请致电JSONCONVER.DESERIALIZEOBJECT方法:

var deserializedTickers = JsonConvert.DeserializeObject<Dictionary<string, Ticker>>(responseBody);

然后,您可以将结果迭代为:

foreach (var ticker in deserializedTickers)
{
    var symbol2 = ticker.Value.Symbol;
}

我有一个错误,当我的一个[可序列化]对象只有1个带有所需arg的构造函数。除序列化时,newtonsoft.json软件包无法从数据中创建实体,因为它在其构造函数中具有所需的参数。

我通过删除构造函数并记住在未从文件/json加载的对象时,请记住调用助手功能。

您可以将root json对象更改为具有属于词典

的属性" tickers"
{
    "tickers":{
        "BTC/AUD": {
            ...
        },
        ...
     }
}

或直接将原始json直接化为字典

var deserializedTickers = JsonConvert.DeserializeObject<Dictionary<string, Ticker>>(responseBody);

您还应该更改信息类以匹配JSON模式

相关内容

最新更新