源代碼 - 主類
string responseBody = await response.Content.ReadAsStringAsync();
status.result deserializeObject = JsonConvert.DeserializeObject<status.result>(responseBody);
Debug.WriteLine(deserializeObject.SafeGasPrice.ToString());
源代碼 - JSON 類
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 反序列化類。
uj5u.com熱心網友回復:
您的資料模型與提供的 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;
或者,您可以對根模型使用匿名型別,如下所示:
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; }
}
}
All this does is define a type result within the scope of another type status. It does not create a property named result within status. As there is no need for such nesting I recommend moving result out from inside status and renaming it Result to follow standard .NET naming conventions.
Demo fiddle here.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/434498.html
標籤:C# json uwp json.net uwp-xml
