首页 > 解决方案 > 如何在 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

标签: c#json

解决方案


其他选择:

  1. 使用属性属性

     [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
     public decimal usDollars { get; set; }
    
  2. 为 JsonSerializer 指定空值处理选项

    var serializerSettings = new JsonSerializerSettings
    {
           NullValueHandling = NullValueHandling.Ignore
    };
    
    List<GoldPrice> goldPrices = JsonConvert.DeserializeObject<List<GoldPrice>>(json, serializerSettings);
    

推荐阅读