[英]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[]>
.我正在寻找反序列化 json object,并且我在我的 json ZA2F2ED4F8EBC2CBB1
Dictionary<string, Name[]>
64C21A29Z40。
How could I access Names
attributes after deserializing my json data?反序列化 json 数据后如何访问
Names
属性?
Json Json
{
"cache": [ {
"data": {
"names": {
"1": [{
"firstname": "John",
"secondname": "Doe"
}],
"2": [{
"firstname": "Alice",
"secondname": "Smith"
}],
"3": [{
"firstname": "John",
"secondname": "John"
}]
}
}
}]
}
Json class 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你可以做这样的事情来打印 Key 和 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()
.您的缓存是一个数组,您可以找到一种方法来遍历其中的每一个。在此示例中,我使用
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.在 foreach 循环中,我正在打印每个
Name[]
的第一个元素,因为这就是 json 示例中的全部内容,但是如果还有更多,您可以通过遍历每个Name
object 来详细说明该方法。
// 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.请处理
null
案例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.