简体   繁体   中英

Get values of an object of dictionary array of object value “ Dictionary<string, object[]>”

I'm looking to deserialize a json object, and I in my json class, I have an attribute of type Dictionary<string, Name[]> .

How could I access Names attributes after deserializing my json data?

Json

{
    "cache": [ {
        "data": {
            "names": {
                "1": [{
                    "firstname": "John",
                    "secondname": "Doe"
                }],
                "2": [{
                     "firstname": "Alice",
                    "secondname": "Smith"
                }],
                "3": [{
                     "firstname": "John",
                    "secondname": "John"
                }]
            }
        }
    }]
}

Json class

// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
//    using Sample;
//
//    var jsonRoot = JsonRoot.FromJson(jsonString);
namespace Sample
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class JsonRoot
    {
        [JsonProperty("cache")]
        public Cache[] Cache { get; set; }
    }

    public partial class Cache
    {
        [JsonProperty("data")]
        public Data Data { get; set; }
    }

    public partial class Data
    {
        [JsonProperty("names")]
        public Dictionary<string, Name[]> Names { get; set; }
    }

    public partial class Name
    {
        [JsonProperty("firstname")]
        public string Firstname { get; set; }

        [JsonProperty("secondname")]
        public string Secondname { get; set; }
    }
}

You can do something like this to print the Key and FirstName

var obj = JsonConvert.DeserializeObject<JsonRoot>(json);
foreach (KeyValuePair<string, Name[]> name in obj.Cache.FirstOrDefault().Data.Names)
{
    Console.WriteLine(name.Key + " " + name.Value.First().Firstname);
}

Your cache is an array, you can find a way to iterate through each of those.. for this example, i used FirstOrDefault() .

In the foreach loop, I am printing the first element of each Name[] since thats all you have in the json example, but you can elaborate the method by iterating through each of the Name object if there are more.

// Prints
1 John
2 Alice
3 John

You can get the required values in the below manner.

JsonRoot root = ......;
var values = root.Cache.Select(x => x.Data).Select(y => y.Names);
foreach( var dictionary in values)
{
    var keys = dictionary.Keys;

    foreach(string key in keys)
    {
        Name[] names = dictionary[key];
    }
}

Please handle the null cases.

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