Converting a JSON.NET JObject's Properties/Tokens into Dictionary Keys

后端 未结 3 1957
醉话见心
醉话见心 2020-12-06 04:52

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 nume

相关标签:
3条回答
  • 2020-12-06 05:00

    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);
    

    Unfortunately it uses explicit interface implementation, which makes this a bit of a pain - but if you go via the IDictionary<string, JToken> interface, it's fine.

    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"]);
        }
    }
    
    0 讨论(0)
  • 2020-12-06 05:08

    Does this work for you?

    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();
    
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-06 05:10

    If you're expecting the child object to have an object property(or field), it's better to use:

    Dictionary<string, object> rates = parsed["rates"].ToObject<Dictionary<string, object>>();
    

    Otherwise, it will throw an error.

    0 讨论(0)
提交回复
热议问题