繁体   English   中英

使用JSON.NET将JSON的一部分反序列化为C#中的数据表

[英]Deserialize part of json to datatable in C# using JSON.NET

这可能非常简单,而我却基本缺乏理解。 我正在调用一个返回JSON的API,如下所示:

{
    disclaimer: "https://openexchangerates.org/terms/",
    license: "https://openexchangerates.org/license/",
    timestamp: 1449877801,
    base: "USD",
    rates: {
        AED: 3.672538,
        AFN: 66.809999,
        ALL: 125.716501,
        AMD: 484.902502,
        ANG: 1.788575,
        AOA: 135.295998,
        ARS: 9.750101,
        AUD: 1.390866,
    }
}   

我要做的就是将结果返回到一个数据表,该表具有Timestamp,base,currency和rate列,其中timestamp和base来自那些字段,而currency和rate来自嵌套的rates部分

我已经花了整整一个上午的时间来阅读并尝试了许多不同的方法,说实话,我离弄清楚自己的需求还很近。 我什至无法阅读基础货币,因为显然stuff.base是不允许的

var response = httpClient.GetStringAsync(new Uri(url)).Result;

JObject jsonResponse = JObject.Parse(response);
CurrentContext.Message.Display(response);

dynamic stuff = JsonConvert.DeserializeObject(response);

var timestamp = stuff.timestamp;
CurrentContext.Message.Display("TIMESTAMP IS :"+ timestamp);

var basecur = stuff.base;
CurrentContext.Message.Display("TIMESTAMP IS :" + basecur);


DataTable outputData = new DataTable();
outputData.Columns.Add("timestamp", typeof(System.String));
outputData.Columns.Add("basecurrency", typeof(System.String));
outputData.Columns.Add("currency", typeof(System.String));
outputData.Columns.Add("rate", typeof(System.Int16));

感谢David的回答,我的代码现已正常运行:

var response = httpClient.GetStringAsync(new Uri(url)).Result;
            var result = JsonConvert.DeserializeObject<Deserialize>(response);

            DataTable outputData = new DataTable();
            outputData.Columns.Add("timestamp", typeof(System.String));
            outputData.Columns.Add("basecurrency", typeof(System.String));
            outputData.Columns.Add("currency", typeof(System.String));
            outputData.Columns.Add("rate", typeof(System.Decimal));

            foreach (KeyValuePair<string, double> entry in result.Rates)
            {

                outputData.Rows.Add(result.Timestamp,result.Base,entry.Key,entry.Value);
            }

            return outputData;

您应该反序列化为适当的C#类,例如:

public class Foo
{
    public string Disclaimer { get; set; }
    public string License { get; set; }
    public int Timestamp { get; set; }
    public string Base { get; set; }
    public Dictionary<string, double> Rates { get; set; }
}

现在您可以执行以下操作:

var result = JsonConvert.DeserializeObject<Foo>(response);

现在,使用其中的数据将变得微不足道:

var baseCurrency = result.Base;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM