c# - 如何在 C# 中解析十进制
问题描述
我正在使用 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
。
解决方案
其他选择:
使用属性属性
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public decimal usDollars { get; set; }
为 JsonSerializer 指定空值处理选项
var serializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; List<GoldPrice> goldPrices = JsonConvert.DeserializeObject<List<GoldPrice>>(json, serializerSettings);
推荐阅读
- entity-framework - EF 包含和 ThenInclude
- flutter - 我如何 navigator.push 一个 showModalBottomSheet 进行颤动?
- javascript - 使用 Feathers JS 4 和 Objection JS 急切加载 - 无法读取未定义的属性“get”
- r - 在数据框中查找单词,返回列名?
- reactjs - 我正在尝试使用 React 和 Axios 调用 Weather API 我正在尝试 console.log 结果但它说未定义... :(
- javascript - 使用 GetElementsByClassName 检查复选框值以及是否以编程方式检查了复选框
- kubernetes - 我可以在离线环境中部署 Kubernetes Dashboard 吗?
- r - 使用group_by和summary时如何输出全部信息
- javascript - 带拖放功能的角度自动滚动
- asp.net - HTTP 错误 404.17 - 未找到 - .NET - IIS 10