【问题标题】:C# JsonConvert Catch Data to Object ErrorC# JsonConvert 捕获数据到对象错误
【发布时间】:2021-09-08 10:43:12
【问题描述】:

我想捕获对象的响应数据

我想声明instant_price 默认使用instant_price_info 来捕捉数组内部的数据,但是我尝试了错误我该怎么办

我想这样怎么办

    public class test
    {
        public test_info test_content { get; set; }

        public test()
        {
            test_content = new test_info();
        }
    }

    public class test_info
    {
        public string info1 { get; set; }
        public string info2 { get; set; }
    }

我创建了 instant_price 类

    public class instant_price
    {
        public Array msgArray { get; set; }

        //public instant_price()
        //{
        //    msgArray = new Array() { List<instant_price_info> };
        //}
    }

    public class instant_price_info
    {
        public string c { get; set; } 
        public string n { get; set; } 
        public string d { get; set; } 
        public string t { get; set; } 
        public string o { get; set; } 
        public string h { get; set; } 
        public string l { get; set; } 
        public string z { get; set; } 
        public string tv { get; set; } 
        public string v{ get; set; } 
        public string a{ get; set; }
        public string b { get; set; } 
    }

这个数据

{
  "msgArray": [
    {
      "tv": "-",
      "ps": "4",
      "pz": "71.3000",
      "fv": "1",
      "oa": "71.1000",
      "ob": "71.0000",
      "c": "4126",
      "d": "20210624",
      "ch": "4126.tw",
      "ot": "14:30:00",
      "g": "7_12_27_15_53_",
      "mt": "000000",
      "ov": "1440",
      "h": "71.3000",
      "i": "22",
      "it": "12",
      "oz": "71.0000",
      "l": "70.8000",
      "t": "13:33:00",
      "y": "70.8000",
      "z": "71.3000",
      "ts": "0"
    }
  ],
  "userDelay": 5000,
  "rtmessage": "OK",
  "cachedAlive": 737684
}

当我捕获响应数据时

instant_price stock = JsonConvert.DeserializeObject<instant_price>(responseResult);

我收到了这个错误代码

Newtonsoft.Json.JsonSerializationException: '无法创建 System.Array 类型的实例。类型是接口或抽象类,不能实例化。路径 'msgArray',第 25 行,位置 13。'

【问题讨论】:

    标签: c# arrays json list jsonconvert


    【解决方案1】:

    由于 JSon 结果是一个数组,您需要使用 list

    list stockList = JsonConvert.DeserializeObject>(responseResult);

    【讨论】:

    • 它不起作用,错误是'无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[instant_price]' 因为该类型需要一个 JSON 数组(例如 [1,2,3])才能正确反序列化。
    猜你喜欢
    • 2019-06-21
    • 1970-01-01
    • 2013-05-23
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    相关资源
    最近更新 更多