繁体   English   中英

JSON 反序列化 object 返回 null

[英]JSON deserialized object returns null

源代码 - 主要 class

        string responseBody = await response.Content.ReadAsStringAsync();

        status.result deserializeObject = JsonConvert.DeserializeObject<status.result>(responseBody);

        Debug.WriteLine(deserializeObject.SafeGasPrice.ToString());

源代码 - JSON Class

    public class status
    {
        public class result
        {
            [JsonProperty(PropertyName = "SafeGasPrice")]
            public int SafeGasPrice { get; set; }

            [JsonProperty(PropertyName = "ProposeGasPrice")]
            public int ProposeGasPrice { get; set; }

            [JsonProperty(PropertyName = "FastGasPrice")]
            public int FastGasPrice { get; set; }
        }
    }

Output

{"status":"1","message":"OK","result":{"LastBlock":"14296250","SafeGasPrice":"96","ProposeGasPrice":"96","FastGasPrice":"97","suggestBaseFee":"95.407119606","gasUsedRatio":"0.174721033333333,0.523179548504219,0.056945596868572,0.999939743363228,0.953861217484817"}}

0

问题

我目前不明白为什么 null 是 output,我的猜测是我错误地实现了 json 反序列化类。

您的数据 model 与提供的 JSON 不对应,它缺少与外部{"result": { }} object 对应的类型:

{
   "status":"1",
   "message":"OK",
   "result":{
      // This inner object corresponds to your model.
      "LastBlock":"14296250",
      "SafeGasPrice":"96",
      "ProposeGasPrice":"96",
      "FastGasPrice":"97",
      "suggestBaseFee":"95.407119606",
      "gasUsedRatio":"0.174721033333333,0.523179548504219,0.056945596868572,0.999939743363228,0.953861217484817"
   }
}

要解决此问题,您需要引入一个外部包装器 model。您可以像这样显式包装:

public class Root
{
    public string status { get; set; }
    public string message { get; set; }
    public Result result { get; set; }
}

public class Result
{
    [JsonProperty(PropertyName = "SafeGasPrice")]
    public int SafeGasPrice { get; set; }

    [JsonProperty(PropertyName = "ProposeGasPrice")]
    public int ProposeGasPrice { get; set; }

    [JsonProperty(PropertyName = "FastGasPrice")]
    public int FastGasPrice { get; set; }
}

像这样反序列化:

var deserializeObject = JsonConvert.DeserializeObject<Root>(responseBody)?.result;

或者,您可以为根 model 使用匿名类型,如下所示:

var deserializeObject = JsonConvert.DeserializeAnonymousType(responseBody, new { result = default(Result) })?.result;

无论哪种方式,您现在都可以成功反序列化内部嵌套属性。

那你做错了什么? 在您的问题中,您将result声明为嵌套类型

public class status
{
    public class result
    {
        [JsonProperty(PropertyName = "SafeGasPrice")]
        public int SafeGasPrice { get; set; }

        [JsonProperty(PropertyName = "ProposeGasPrice")]
        public int ProposeGasPrice { get; set; }

        [JsonProperty(PropertyName = "FastGasPrice")]
        public int FastGasPrice { get; set; }
    }
}

所有这一切都是在 scope 中定义另一种类型status的类型result 它不会在status中创建名为result属性 由于不需要这样的嵌套,我建议将result从内部status中移出并将其重命名为Result以遵循标准的 .NET 命名约定。

演示小提琴在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM