转换一个JSON.NET JObject的属性/令牌,字典键 [英] Converting a JSON.NET JObject's Properties/Tokens into Dictionary Keys

查看:120
本文介绍了转换一个JSON.NET JObject的属性/令牌,字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JSON.NET解析从openexhangerates.org服务器端使用.NET一个JSON效应初探。响应包含一个嵌套的对象(差饷),其中有数值属性的一个长长的清单:

I'm using JSON.NET to parse a JSON reponse from openexhangerates.org server side using .NET. The response contains a nested object ("rates") which has a long list of numeric properties:

    {
    "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...
        }
    }

属性名称对应于货币类型(例如: 美元)。我需要假设属性的列表可以随时间而改变,所以我想将对象转换成一个字典,而不是一个相应的C#对象。

The property names correspond to the currency type (e.g. "USD"). I need to assume that the list of properties can change over time, so I want to convert the object into a Dictionary instead of a corresponding C# object.

因此​​,而不是反序列化JSON对象弄成这个样子:

So instead of deserializing the JSON object into something like this:

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...
}



我想结束了这一点:

I want to end up with this:

Dictionary<string,decimal>() {{"AED",0.2828},{"AFN",0.3373},{"ALL",2.2823},{"AMD",33.378} // etc...};



我如何做到这一点无论从响应字符串或致电JObject.Parse产生的JObject开始(responseString)?

How do I do this starting from either the response string or from the JObject produced by calling JObject.Parse(responseString)?

推荐答案

JObject 已经实现了 IDictionary的<字符串,JToken> ,所以我怀疑,当您浏览到的成员,你应该能够使用:

JObject already implements IDictionary<string, JToken>, so I suspect that when you've navigated down to the rates member, you should be able to use:

var result = rates.ToDictionary(pair => pair.Key, pair => (decimal) pair.Value);



不幸的是,它使用显式接口实现,这使它成为一个有点痛 - 但是如果你通过去在的IDictionary<字符串,JToken> 接口,它的罚款

下面是这似乎工作很短,但完整的例子。与您所提供的JSON(保存到 test.json 文件):

Here's a short but complete example which appears to work with the JSON you've provided (saved into a test.json file):

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

class Test
{
    static void Main()
    {
        JObject parsed = JObject.Parse(File.ReadAllText("test.json"));
        IDictionary<string, JToken> rates = (JObject) parsed["rates"];
        // Explicit typing just for "proof" here
        Dictionary<string, decimal> dictionary =
            rates.ToDictionary(pair => pair.Key,
                               pair => (decimal) pair.Value);
        Console.WriteLine(dictionary["ALL"]);
    }
}

这篇关于转换一个JSON.NET JObject的属性/令牌,字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆