JSON 反序列化对象 returns 空

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; }
        }
    }

输出

{"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,我的猜测是我没有正确实现 json 反序列化 classes。

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

{
   "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"
   }
}

要解决此问题,您需要引入外部包装模型。你可以像这样做一个明确的:

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;

或者,您可以像这样对根模型使用 anonymous type

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

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

那你做错了什么?在您的问题中,您将 result 声明为 nested type:

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; }
    }
}

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

演示 fiddle here.