提问者:小点点

有没有更优雅的方法使用System.Text.JSON从JSON对象获取特定值


考虑这个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次?


共2个答案

匿名用户

如果您只需要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.JSONAPI,则可以先将JSON解析为JSONDocument,然后枚举其属性。 首先获取main对象,然后扁平化其子属性,并按iddomain名称筛选它们

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();