【发布时间】:2021-04-25 09:27:25
【问题描述】:
我正在使用 C#、UWP 和 Newtonsoft.Json 库将文本解析为 json。
我要解析的数据是:
[
{
"id": 9,
"displayNo": 1,
"ygnGoldPrice": 1111111.00,
"worldGoldPrice": 33333.00,
"usDollars": 1640.00,
"differenceGoldPrice": 12000.00,
"updatedDate": "2021-04-23T14:59:11Z"
},
{
"id": 10,
"displayNo": 2,
"ygnGoldPrice": 12345.00,
"worldGoldPrice": 1222.00,
"usDollars": null,
"differenceGoldPrice": 1222.00,
"updatedDate": "2021-04-23T15:01:23Z"
}
]
如您所见,某些字段有小数点.00,我正在尝试使用以下模型对其进行解析。
class GoldPrice
{
public int id { get; set; }
public int displayNo { get; set; }
public decimal ygnGoldPrice { get; set; }
public decimal worldGoldPrice { get; set; }
public decimal usDollars { get; set; }
public decimal differenceGoldPrice { get; set; }
public string updatedDate { get; set; }
}
解析的方法
public async Task<ObservableCollection<T>> GetAll<T>(ObservableCollection<T> list, string path = "")
{
HttpClient httpClient = new HttpClient();
Uri requestUri = new Uri(baseUri + path);
HttpResponseMessage httpResponse = new HttpResponseMessage();
string httpResponseBody;
try
{
httpResponse = await httpClient.GetAsync(requestUri);
httpResponse.EnsureSuccessStatusCode();
httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
Debug.WriteLine(httpResponseBody); // The data is printed out. OK.
return JsonConvert.DeserializeObject<ObservableCollection<T>>(httpResponseBody);
}
catch (Exception ex)
{
httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
return null;
}
}
我在return JsonConvert.DeserializeObject... 行中收到以下错误
Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll.
【问题讨论】:
-
您的我们的 Dollars 为空值,但该属性不可为空
-
属性 updateDate 也可以是 DateTime 类型
-
连续挣扎了大约 3 个小时,我明白了。这是因为空。如何在我的模型中声明可为空?
-
public decimal? usDollars { get; set; },注意?