C# 转换JSON.NET作业对象';将属性/标记转换为字典键
我正在使用JSON.NET解析openexhangerates.org服务器端使用.NET的JSON响应。响应包含一个嵌套对象(“速率”),该对象具有一长串数字属性:C# 转换JSON.NET作业对象';将属性/标记转换为字典键,c#,.net,json.net,C#,.net,Json.net,我正在使用JSON.NET解析openexhangerates.org服务器端使用.NET的JSON响应。响应包含一个嵌套对象(“速率”),该对象具有一长串数字属性: { "disclaimer": "Exchange rates provided for informational purposes only, with no guarantee whatsoever of accuracy, validity, availability, or fitness for any
{
"disclaimer": "Exchange rates provided for informational purposes only, with no guarantee whatsoever of accuracy, validity, availability, or fitness for any purpose; use at your own risk. Other than that, have fun! Usage subject to acceptance of terms: http://openexchangerates.org/terms/",
"license": "Data sourced from various providers with public-facing APIs; copyright may apply; not for resale; no warranties given. Usage subject to acceptance of license agreement: http://openexchangerates.org/license/",
"timestamp": 1357268408,
"base": "USD",
"rates": {
"AED": 3.673033,
"AFN": 51.5663,
"ALL": 106.813749,
"AMD": 403.579996,
etc...
}
}
财产名称对应于货币类型(例如“USD”)。我需要假设属性列表可以随时间变化,因此我想将对象转换为字典,而不是相应的C#对象
因此,与其将JSON对象反序列化为如下内容:
class Rates
{
public decimal AED; // United Arab Emirates Dirham
public decimal AFN; // Afghan Afghani
public decimal ALL; // Albanian Lek
public decimal AMD; // Armenian Dram
// etc...
}
我想以这个结尾:
Dictionary<string,decimal>() {{"AED",0.2828},{"AFN",0.3373},{"ALL",2.2823},{"AMD",33.378} // etc...};
Dictionary();
如何从响应字符串或调用JObject.Parse(responseString)生成的JObject开始执行此操作?
JObject
已经实现了IDictionary
,因此我怀疑当您导航到rates
成员时,您应该能够使用:
var result = rates.ToDictionary(pair => pair.Key, pair => (decimal) pair.Value);
不幸的是,它使用了显式的接口实现,这让它有点麻烦-但是如果您通过IDictionary
接口,它就可以了
下面是一个简短但完整的示例,它似乎与您提供的JSON(保存到test.JSON
文件中)一起工作:
使用系统;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
使用Newtonsoft.Json.Linq;
课堂测试
{
静态void Main()
{
JObject parsed=JObject.Parse(File.ReadAllText(“test.json”);
IDictionary rates=(JObject)解析[“rates”];
//这里显式键入只是为了“证明”
字典=
rates.ToDictionary(pair=>pair.Key,
pair=>(十进制)pair.Value);
Console.WriteLine(字典[“全部]);
}
}
这对你有用吗
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace JsonNetTest
{
class Program
{
static void Main(string[] args)
{
string jsonString = @"{
'disclaimer': 'Exchange rates provided for informational purposes only, with no guarantee whatsoever of accuracy, validity, availability, or fitness for any purpose; use at your own risk. Other than that, have fun! Usage subject to acceptance of terms: http://openexchangerates.org/terms/',
'license': 'Data sourced from various providers with public-facing APIs; copyright may apply; not for resale; no warranties given. Usage subject to acceptance of license agreement: http://openexchangerates.org/license/',
'timestamp': 1357268408,
'base': 'USD',
'rates': {
'AED': 3.673033,
'AFN': 51.5663,
'ALL': 106.813749,
'AMD': 403.579996
}
}";
JObject parsed = JObject.Parse(jsonString);
Dictionary<string, decimal> rates = parsed["rates"].ToObject<Dictionary<string, decimal>>();
Console.WriteLine(rates["ALL"]);
Console.ReadKey();
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用Newtonsoft.Json.Linq;
名称空间JSONNETSET
{
班级计划
{
静态void Main(字符串[]参数)
{
字符串jsonString=@”{
“免责声明”:“提供的汇率仅供参考,不保证其准确性、有效性、可用性或适用性;使用风险自负。除此之外,请尽情享受!使用时须遵守以下条款:http://openexchangerates.org/terms/',
“许可证”:“数据来源于具有面向公众的API的各种提供商;版权可能适用;不用于转售;不提供任何担保。使用取决于许可协议的接受:http://openexchangerates.org/license/',
“时间戳”:1357268408,
“基数”:美元,
“费率”:{
“AED”:3.673033,
“AFN”:51.5663,
“全部”:106.813749,
“AMD”:403.579996
}
}";
JObject parsed=JObject.Parse(jsonString);
字典速率=已解析[“速率”]。ToObject();
控制台写入线(费率[“全部]);
Console.ReadKey();
}
}
}
如果希望子对象具有对象属性(或字段),最好使用:
Dictionary<string, object> rates = parsed["rates"].ToObject<Dictionary<string, object>>();
Dictionary rates=parsed[“rates”].ToObject();
否则,它将抛出一个错误 你看过谷歌关于如何使用C反序列化JSON的搜索结果了吗?互联网上有很多例子。。我如何“导航”到“费率”?当我尝试使用jo[“rates”]时,得到一个JToken-back,而不是JObject。@Canoehead:你需要转换到
JObject
。请参阅我的编辑以获取完整的示例。您永远不会停止对您的知识和帮助感到惊讶!我使用它从JSON中获取一些值。但是,我们如何使用相同的方法在字典中获取整个JSON,而不仅仅是“速率”?我应该如何将其用于多维JSON对象?我想提取键和值的字符串值-这只适用于第一级;在那之后,它仍然是编码的作业对象。我发现这是访问密钥的最简单方法。我用你的答案来回答
Dictionary<string, object> rates = parsed["rates"].ToObject<Dictionary<string, object>>();