简体   繁体   中英

Deserializing key value pair into list

Can anyone please show me how to deserialize key-value pair into a list? ie From the JSON response, I want to get out the list of countries and code from below response. I am using Newtonsoft.Json:

{
    "status": "SUCCESS",
    "message": "something",
    "data": {
        "trade_origin_iso3country": "GBR",
        "countries": {
            "ARM ": "Armenia",
            "BLR": "Belarus ",
            "DNK": "Denmark",
            "GBR": "United Kingdom",
            "MCO": "Monaco"
        }
    }
}

If you create a class with the following definition:

public class MyObject 
{
     public string status { get; set; }
     public string message { get; set; }
     public MySubObject data { get; set; }
}

public class MySubObject 
{
    public string trade_origin_iso3country { get; set;}
    public Dictionary<string,string> countries { get;set;}
}

You can just use the most convenient ( at least IMO) syntax to get an object with a filled dictionary.

var myResult = JsonConvert.Deserialize<MyObject>(json);

To get a list:

var result = (
     from kvp in myResult.data.countries
     select $"{kvp.Key}: {kvp.Value}").ToList()

You could use JObject.Parse to parse json to JObject and then access the inner property and convert it to Dictionary<string, string> :

var countries = JObject.Parse(json)["data"]["countries"].ToObject<Dictionary<string, string>>();
foreach (var kv in countries)
{
    Console.WriteLine($"Key[{kv.Key}] Value[{kv.Value}]");
}

Will output:

Key[ARM] Value[Armenia]
... etc.
var data = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

foreach(var kv in data)
{
Console.WriteLine(kv.Key + ":" + kv.Value);
}

try this

I recommend custom types if that's possible. Here's a console app you can copy and paste that shows you what I'm referring to using the information you've provided. It uses the well known and highly recommended Newtonsoft.Json nuget package.

Code:

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

namespace Question_Answer_Console_App
{
    public class Program
    {
        public const string JsonResultString = @"{
                                                     ""status"": ""SUCCESS"",
                                                     ""message"": ""something"",
                                                     ""data"": {
                                                         ""trade_origin_iso3country"": ""GBR"",
                                                         ""countries"": {
                                                             ""ARM"": ""Armenia"",
                                                             ""BLR"": ""Belarus "",
                                                             ""DNK"": ""Denmark"",
                                                             ""GBR"": ""United Kingdom"",
                                                             ""MCO"": ""Monaco""
                                                         }
                                                     }
                                                 }";
        [STAThread]
        static void Main(string[] args)
        {
            var jsonResult = JsonConvert.DeserializeObject<JsonResult>(JsonResultString);

            foreach (var keyValue in jsonResult.Data.Countries)
                Console.WriteLine($"{keyValue.Key} : {keyValue.Value}");

            Console.Read();
        }
    }

    public class JsonResult
    {
        public string Status { get; set; }
        public string Message { get; set; }
        public JsonData Data { get; set; }
    }

    public class JsonData
    {
        [JsonProperty("trade_origin_iso3country")]
        public string TradeOriginIso3country { get; set; }
        public Dictionary<string, string> Countries { get; set; }
    }
}

Outputs:

ARM : Armenia
BLR : Belarus
DNK : Denmark
GBR : United Kingdom
MCO : Monaco

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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