考虑这个Json对象:
{
"main": {
"2058": {
"id": "2058",
"name": "foo",
"attrib1": "17",
"domain": "somewhere.net",
"enabled": "1",
"permissions": [
"admin",
"user",
"guest",
"vpn",
"power"
]
}
},
"validate": {
"2058": {
"id": "2058",
"name": "foo",
"attrib1": "17",
"domain": "somewhere.net",
"enabled": "1",
"permissions": [
"admin",
"user",
"guest",
"vpn",
"power"
]
}
},
"result": "ok"
}
在“enabled”和“permissions”之间,还有几百对我漏掉了。 “validate”部分与“main”完全相同,“result”就是结果。
我想从主要部分得到2个具体的值。 “ID”和“域”。 我使用下面的代码来执行此操作。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
namespace JsonParse
{
class Program
{
static void Main()
{
string json = "{" +
"\"main\":{" +
"\"2058\":{" +
"\"id\":\"2058\"," +
"\"name\":\"foo\"," +
"\"attrib1\":\"17\"," +
"\"domain\":\"somewhere.net\"," +
"\"enabled\":\"1\"," +
"\"permissions\":[\"admin\",\"user\",\"guest\",\"vpn\",\"power\"]" +
"}" +
"}," +
"\"validate\":{" +
"\"2058\":{" +
"\"id\":\"2058\"," +
"\"name\":\"foo\"," +
"\"attrib1\":\"17\"," +
"\"domain\":\"somewhere.net\"," +
"\"enabled\":\"1\"," +
"\"permissions\":[\"admin\",\"user\",\"guest\",\"vpn\",\"power\"]" +
"}" +
"}," +
"\"result\":\"ok\"" +
"}";
foreach (KeyValuePair<string, object> item in JsonSerializer.Deserialize<Dictionary<string, object>>(json))
{
if (item.Key == "main")
{
Dictionary<string, object> pairs = JsonSerializer.Deserialize<Dictionary<string, object>>(item.Value.ToString());
Dictionary<string, object> pairs1 = JsonSerializer.Deserialize<Dictionary<string, object>>(pairs.First().Value.ToString());
foreach (KeyValuePair<string, object> valuePair in pairs1)
{
if (valuePair.Key == "id" || valuePair.Key == "domain")
{
Console.WriteLine("Key: " + valuePair.Key + "\nValue: " + valuePair.Value);
}
}
}
}
}
}
}
从这里,我得到了“2058”和“somewhere.net”,但是有没有更优雅的方法来获得这些值,而不是反序列化3次?
如果您只需要main
属性,则可以使用json路径通过Newtonsoft json.NET选择所有“main”:
var pairs = JObject.Parse(js).SelectTokens("$.main.*")
.Select(j => (id:j["id"],domain: j["domain"]))
.ToList();
或者仅反序列化为相应的结构(使用system.text.json
或Newtonsoft):
class MyClass
{
public Dictionary<string, InnerClass> main { get; set; }
}
class InnerClass
{
public string id { get; set; }
public string domain { get; set; }
}
ICollection<InnerClass> mains= JsonSerializer.Deserialize<MyClass>(js).main.Values; // System.Text.Json
如果您使用的是System.Text.JSON
API,则可以先将JSON解析为JSONDocument
,然后枚举其属性。 首先获取main
对象,然后扁平化其子属性,并按id
和domain
名称筛选它们
using var document = JsonDocument.Parse(jsonString);
var main = document.RootElement.EnumerateObject().FirstOrDefault(p => p.Name == "main");
var properties = main.Value.EnumerateObject().SelectMany(p => p.Value.EnumerateObject()).ToList();
var id = properties.FirstOrDefault(p => p.Name == "id").Value.GetString();
var domain = properties.FirstOrDefault(p => p.Name == "domain").Value.GetString();