我想反序列化一个json对象,在我的json类中,我有一个类型为Dictionary<string, Name[]>
的属性。
在反序列化json数据后,如何访问Names
属性?
Json
{
"cache": [ {
"data": {
"names": {
"1": [{
"firstname": "John",
"secondname": "Doe"
}],
"2": [{
"firstname": "Alice",
"secondname": "Smith"
}],
"3": [{
"firstname": "John",
"secondname": "John"
}]
}
}
}]
}
Json级
// 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; }
}
}
您可以这样做来打印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);
}
你的缓存是一个数组,你可以找到一种方法来迭代其中的每一个。。对于这个例子,我使用了FirstOrDefault()
。
在foreach循环中,我打印每个Name[]
的第一个元素,因为这就是json示例中的全部内容,但如果有更多内容,您可以通过迭代每个Name
对象来详细说明该方法。
// Prints
1 John
2 Alice
3 John
您可以通过以下方式获得所需的值。
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];
}
}
请处理null
案件。