【问题标题】:Trying to deserialze JSON returns null values尝试反序列化 JSON 返回空值
【发布时间】:2022-12-03 02:47:46
【问题描述】:

使用方法 JsonConvert.DeserializeObject 返回所有属性的默认值。

var current = JsonConvert.DeserializeObject<Current>(myJson);
{
    "location": {
        "name": "London"
    },
    "current": {
        "temp_c": 5.0,
        "cloud": 50
    }
}
public class Current
    {
        public double Temp_c { get; set; }

        public double Cloud { get; set; }
    }

预期的当前对象应具有以下值:Cloud 为 50,Temp_c 为 5.0。

【问题讨论】:

    标签: c# json json.net


    【解决方案1】:

    您需要定义一个类模型,如 json 对象 然后反序列化它

    public class YourModel {
    
       //create location class that has Name property
       public Location Location { get; set; }
    
       //create current class that has Temp_c and Cloud property
       public Current Current { get; set; }
    
    }
    

    接着

    var data = JsonConvert.DeserializeObject<YourModel>(myJson);
    

    并从数据对象中获取当前值

    var current = data.Current;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      相关资源
      最近更新 更多