【问题标题】:Deserialize JSON data in to a class in c#在c#中将JSON数据反序列化到一个类中
【发布时间】:2018-06-03 15:32:09
【问题描述】:

大家好,我有这个 Json 数据: https://openexchangerates.org/api/latest.json?app_id=6cf59607a32d408eb3e04de1427a3169

我想在下面的类中反序列化

 using Newtonsoft.Json;
using System.Collections.Generic;

namespace Divisas2MVVM2.Classes

{
public class ExchangeRates
{
    [JsonProperty(PropertyName = "disclaimer")]
    public string Disclaimer { get; set; }

    [JsonProperty(PropertyName = "license")]
    public string License { get; set; }

    [JsonProperty(PropertyName = "timestamp")]
    public int TimeStamp { get; set; }

    [JsonProperty(PropertyName = "base")]
    public string Base { get; set; }

    [JsonProperty(PropertyName = "rates")]
    public Rates Rates { get; set; }
}

public class Rates
{
    public double AED { get; set; }
    public double AFN { get; set; }
    public double ALL { get; set; }
    public double AMD { get; set; }
    // I cut the text so that it would not be to long
    public double ZMW { get; set; }
    public double ZWL { get; set; }
}

public class Rate
{
    public double TaxRate { get; set; }

    public string Code { get; set; }
}

这是我的属性

 private ExchangeRates exchangeRates;

我的 MainViewModel 的构造函数

new ObservableCollection data
Rates = new ObservableCollection<Rate>();

并在此方法中获取 json 数据

 try
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri("https://openexchangerates.org");
            var url = "/api/latest.json?app_id=6cf59607a32d408eb3e04de1427a3169";
            var response = await client.GetAsync(url);

            if (!response.IsSuccessStatusCode)
            {
                Message = response.StatusCode.ToString();
                IsRunning = false;
                return;
            }

            var result = await response.Content.ReadAsStringAsync();
            exchangeRates = JsonConvert.DeserializeObject<ExchangeRates>(result);

        }

一切正常,变量 result 具有正确的字符串格式的 json 数据,但是当我调用 JsonConvert 时。 DeserializeObject,数据“速率”未正确分配,所有其他数据:免责声明”、“许可证”、“时间戳”等均已正确分配。只有速率失败。

the string is correct

other data is correct in the class

rates is incorrect

对不起我的英语我希望你能理解我:)

【问题讨论】:

  • 您的问题是什么? Newtonsoft 文档有很多关于如何做到这一点的例子。您是否遇到错误或异常?如果有,是什么?
  • 对不起,我编辑并解释了我的问题
  • 您的模型无法成功解析费率数据,正在寻找解决方案

标签: json xamarin.forms json.net


【解决方案1】:

使用它作为你的模型类

namespace Rate
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class Rates
    {
        [JsonProperty("disclaimer")]
        public string Disclaimer { get; set; }

        [JsonProperty("license")]
        public string License { get; set; }

        [JsonProperty("timestamp")]
        public long Timestamp { get; set; }

        [JsonProperty("base")]
        public string Base { get; set; }

        [JsonProperty("rates")]
        public Dictionary<string, double> RatesRates { get; set; }
    }

    public partial class Rates
    {
        public static Rates FromJson(string json) => JsonConvert.DeserializeObject<Rates>(json, Rate.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this Rates self) => JsonConvert.SerializeObject(self, Rate.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters = {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}

然后在你的课堂上这样做

            var data = Rate.Rates.FromJson("jsonresult");


            var  rate = data.RatesRates;
            foreach (var pair in rate)
            {
                string symbol = pair.Key;  //"AED"
                double value = pair.Value; //3.673175,
            }


var time = data.Timestamp;
            var disclaimer = data.Disclaimer;
            var license = data.License;

测试和工作

【讨论】:

  • 非常感谢!这会儿我要试试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多