如何使用 System.Text.Json 从 json 中读取简单值?

问题描述 投票:0回答:10

我有这个json

{"id":"48e86841-f62c-42c9-ae20-b54ba8c35d6d"}

如何从中取出

48e86841-f62c-42c9-ae20-b54ba8c35d6d
?我能找到的所有示例都表明可以做类似的事情

var o = System.Text.Json.JsonSerializer.Deserialize<some-type>(json);
o.id // <- here's the ID!

但是我没有符合这个定义的类型,并且我不想创建一个类型。我尝试过反序列化为动态,但无法正常工作。

var result = System.Text.Json.JsonSerializer.Deserialize<dynamic>(json);
result.id // <-- An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Linq.Expressions.dll but was not handled in user code: ''System.Text.Json.JsonElement' does not contain a definition for 'id''

有人可以给点建议吗?


编辑:

我刚刚发现我可以做到这一点:

Guid id = System.Text.Json.JsonDocument.Parse(json).RootElement.GetProperty("id").GetGuid();

这确实有效 - 但有更好的方法吗?

c# .net-core system.text.json
10个回答
58
投票

您可以反序列化为

Dictionary
:

var dict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, string>>(json)

或者只是反序列化为

Object
,这将产生一个
JsonElement
,您可以调用
GetProperty


31
投票

使用

JsonObject
.NET 6
中添加了对
System.Text.Json.Nodes
的支持。

示例:

const string Json = "{\"MyNumber\":42, \"MyArray\":[10,11]}";
// dynamic
{
    dynamic obj = JsonNode.Parse(Json);
    int number = (int)obj["MyNumber"];
    Debug.Assert(number == 42);

    obj["MyString"] = "Hello";
    Debug.Assert((string)obj["MyString"] == "Hello");
}

// JsonObject 
{
    JsonObject obj = JsonNode.Parse(Json).AsObject();
    int number = (int)obj["MyNumber"];
    Debug.Assert(number == 42);
    
    obj["MyString"] = "Hello";
    Debug.Assert((string)obj["MyString"] == "Hello");
}

来源:

https://github.com/dotnet/runtime/issues/53195

https://github.com/dotnet/runtime/issues/45188


17
投票

我最近将一个项目从 ASP.NET Core 2.2 迁移到 3,遇到了这种不便。在我们的团队中,我们重视精益依赖关系,因此我们试图避免包含 Newtonsoft.JSON 并尝试使用

System.Text.Json
。我们还决定不使用大量 POCO 对象来进行 JSON 序列化,因为我们的后端模型比 Web API 所需的更复杂。此外,由于不平凡的行为封装,后端模型不能轻松地用于序列化/反序列化 JSON 字符串。

我知道

System.Text.Json
应该比 Newtonsoft.JSON 更快,但我相信这与来自/到特定 POCO 类的 ser/deser 有很大关系。不管怎样,速度并不在我们这个决定的利弊列表中,所以 YMMV。

长话短说,目前我编写了一个小型动态对象包装器,它从 System.Text.Json 中解压

JsonElement
并尝试尽可能地进行转换/转换。典型用法是将请求主体作为动态对象读取。再说一次,我很确定这种方法会消除任何速度增益,但这不是我们的用例所关心的问题。

这是班级:

    public class ReflectionDynamicObject : DynamicObject {
        public JsonElement RealObject { get; set; }

        public override bool TryGetMember (GetMemberBinder binder, out object result) {
            // Get the property value
            var srcData = RealObject.GetProperty (binder.Name);

            result = null;

            switch (srcData.ValueKind) {
                case JsonValueKind.Null:
                    result = null;
                    break;
                case JsonValueKind.Number:
                    result = srcData.GetDouble ();
                    break;
                case JsonValueKind.False:
                    result = false;
                    break;
                case JsonValueKind.True:
                    result = true;
                    break;
                case JsonValueKind.Undefined:
                    result = null;
                    break;
                case JsonValueKind.String:
                    result = srcData.GetString ();
                    break;
                case JsonValueKind.Object:
                    result = new ReflectionDynamicObject {
                        RealObject = srcData
                    };
                    break;
                case JsonValueKind.Array:
                    result = srcData.EnumerateArray ()
                        .Select (o => new ReflectionDynamicObject { RealObject = o })
                        .ToArray ();
                    break;
            }

            // Always return true; other exceptions may have already been thrown if needed
            return true;
        }
    }

这是一个示例用法,用于解析请求正文 - 其中一部分位于我所有 WebAPI 控制器的基类中,它将正文公开为动态对象:

    [ApiController]
    public class WebControllerBase : Controller {

        // Other stuff - omitted

        protected async Task<dynamic> JsonBody () {
            var result = await JsonDocument.ParseAsync (Request.Body);
            return new ReflectionDynamicObject {
                RealObject = result.RootElement
            };
        }
    }

并且可以像这样在实际控制器中使用:

//[...]
    [HttpPost ("")]
    public async Task<ActionResult> Post () {
        var body = await JsonBody ();
        var name = (string) body.Name;
        //[...]
    }
//[...]

如果需要,您可以根据需要集成 GUID 或其他特定数据类型的解析 - 而我们都在等待一些官方/框架认可的解决方案。


11
投票

在 System.Text.Json 中解析字符串的实际方法(.NET Core 3+)

        var jsonStr = "{\"id\":\"48e86841-f62c-42c9-ae20-b54ba8c35d6d\"}";
        using var doc = JsonDocument.Parse(jsonStr);
        var root = doc.RootElement;
        var id = root.GetProperty("id").GetGuid();

4
投票

我为此编写了一个扩展方法。您可以按照以下方式安全使用:

var jsonElement = JsonSerializer.Deserialize<JsonElement>(json);
var guid = jsonElement.TryGetValue<Guid>("id");

这是扩展类。

public static class JsonElementExtensions
{
    private static readonly JsonSerializerOptions options = new() { PropertyNameCaseInsensitive = true };

    public static T? TryGetValue<T>(this JsonElement element, string propertyName)
    {
        if (element.ValueKind != JsonValueKind.Object)
        {
            return default;
        }

        element.TryGetProperty(propertyName, out JsonElement property);

        if (property.ValueKind == JsonValueKind.Undefined ||
            property.ValueKind == JsonValueKind.Null)
        {
            return default;
        }

        try
        {
            return property.Deserialize<T>(options);
        }
        catch (JsonException)
        {
            return default;
        }
    }
}

原因

使用此扩展而不是

JsonNode
类的原因是因为如果您需要
Controller
方法只接受
object
而不暴露其模型类 Asp.Net Core 模型绑定使用
JsonElement
结构来映射 json 字符串。目前(据我所知)没有简单的方法将
JsonElement
转换为
JsonNode
并且当您的对象可以是任何对象时,
JsonElement
方法将为未定义的字段抛出异常,而
JsonNode
不会抛出异常.

[HttpPost]
public IActionResult Post(object setupObject)
{
    var setup = (JsonElement)setupObject;
    var id = setup.TryGetValue<Guid>("id");
    var user = setup.TryGetValue<User?>("user");
    var account = setup.TryGetValue<Account?>("account");
    var payments = setup.TryGetValue<IEnumerable<Payments>?>("payments");

    // ...

    return Ok();
}

1
投票

您可以使用以下扩展方法来查询“xpath”等数据

public static string? JsonQueryXPath(this string value, string xpath, JsonSerializerOptions? options = null) => value.Deserialize<JsonElement>(options).GetJsonElement(xpath).GetJsonElementValue();

        
        public static JsonElement GetJsonElement(this JsonElement jsonElement, string xpath)
        {
            if (jsonElement.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined)
                return default;

            string[] segments = xpath.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries);

            foreach (var segment in segments)
            {
                if (int.TryParse(segment, out var index) && jsonElement.ValueKind == JsonValueKind.Array)
                {
                    jsonElement = jsonElement.EnumerateArray().ElementAtOrDefault(index);
                    if (jsonElement.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined)
                        return default;

                    continue;
                }

                jsonElement = jsonElement.TryGetProperty(segment, out var value) ? value : default;

                if (jsonElement.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined)
                    return default;
            }

            return jsonElement;
        }

        public static string? GetJsonElementValue(this JsonElement jsonElement) => jsonElement.ValueKind != JsonValueKind.Null &&
                                                                                   jsonElement.ValueKind != JsonValueKind.Undefined
            ? jsonElement.ToString()
            : default;

简单使用如下

string raw = @"{
        ""data"": {
        ""products"": {
            ""edges"": [
                {
                    ""node"": {
                        ""id"": ""gid://shopify/Product/4534543543316"",
                        ""featuredImage"": {
                            ""originalSrc"": ""https://cdn.shopify.com/s/files/1/0286/pic.jpg"",
                            ""id"": ""gid://shopify/ProductImage/146345345339732""
                        }
                    }
                },
                {
                    ""node"": {
                        ""id"": ""gid://shopify/Product/123456789"",
                        ""featuredImage"": {
                            ""originalSrc"": ""https://cdn.shopify.com/s/files/1/0286/pic.jpg"",
                            ""id"": [
                                ""gid://shopify/ProductImage/123456789"",
                                ""gid://shopify/ProductImage/666666666""
                            ]
                        },
                        ""1"": {
                            ""name"": ""Tuanh""
                        }
                    }
                }
            ]
        }
        }
    }";

            System.Console.WriteLine(raw2.QueryJsonXPath("data.products.edges.0.node.featuredImage.id"));

0
投票

在 .NET 6 Azure HTTPTrigger Function 中为我工作的解决方案,无需使用类对象

    [Function("HTTPTrigger1")]
    public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
    {
        // Input: { "name": "Azure", "id": 123 }
        var reqBody = new StreamReader(req.Body).ReadToEnd();
        JsonObject obj = JsonNode.Parse(reqBody).AsObject();
        obj.TryGetPropertyValue ("name", out JsonNode jsnode);
        string name2 = jsnode.GetValue<string>();
        obj.TryGetPropertyValue ("id", out jsnode);
        int id2 = jsnode.GetValue<int>();

        // OR
        // using dictionary
        var data = JsonSerializer.Deserialize<Dictionary<string, object>> (reqBody);
        string name = data["name"].ToString () ?? "Anonymous";
        int.TryParse(data["id"].ToString(), out int id);

        _logger.LogInformation($"Hi {name}{id} {name2}{id2}. C# HTTP trigger function processed a request.");
        var response = req.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
        response.WriteString("Welcome to Azure Functions!");
        return response;
    }

这是我用于快速测试目的而不是干净的 POCO 对象。


0
投票

只需这样做:

var obj = System.Text.Json.JsonSerializer.Deserialize<JsonNode>(jsonString);
var id = obj["id"]; // <- here's the ID!

-1
投票

更新至.NET Core 3.1以支持

public static dynamic FromJson(this string json, JsonSerializerOptions options = null)
    {
        if (string.IsNullOrEmpty(json))
            return null;

        try
        {
            return JsonSerializer.Deserialize<ExpandoObject>(json, options);
        }
        catch
        {
            return null;
        }
    }

-1
投票

您还可以将 json 反序列化为目标类的对象,然后按正常方式读取其属性:

var obj = DeSerializeFromStrToObj<ClassToSerialize>(jsonStr);
Console.WriteLine($"Property: {obj.Property}");

其中

DeSerializeFromStrToObj
是一个自定义类,它利用反射来实例化目标类的对象:

    public static T DeSerializeFromStrToObj<T>(string json)
    {
        try
        {
            var o = (T)Activator.CreateInstance(typeof(T));

            try
            {
                var jsonDict = JsonSerializer.Deserialize<Dictionary<string, string>>(json);

                var props = o.GetType().GetProperties();

                if (props == null || props.Length == 0)
                {
                    Debug.WriteLine($"Error: properties from target class '{typeof(T)}' could not be read using reflection");
                    return default;
                }

                if (jsonDict.Count != props.Length)
                {
                    Debug.WriteLine($"Error: number of json lines ({jsonDict.Count}) should be the same as number of properties ({props.Length})of our class '{typeof(T)}'");
                    return default;
                }

                foreach (var prop in props)
                {
                    if (prop == null)
                    {
                        Debug.WriteLine($"Error: there was a prop='null' in our target class '{typeof(T)}'");
                        return default;
                    }

                    if (!jsonDict.ContainsKey(prop.Name))
                    {
                        Debug.WriteLine($"Error: jsonStr does not refer to target class '{typeof(T)}'");
                        return default;
                    }

                    var value = jsonDict[prop.Name];
                    Type t = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                    object safeValue = value ?? Convert.ChangeType(value, t);
                    prop.SetValue(o, safeValue, null); // initialize property
                }
                return o;
            }
            catch (Exception e2)
            {
                Debug.WriteLine(e2.Message);
                return o;
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.Message);
            return default;
        }
    }

例如,您可以测试您的 jsons here

在这里您可以找到一个完整的工作示例,其中包含您和/或未来的读者可能感兴趣的不同序列化和反序列化方式:

using System;
using System.Collections.Generic;
using System.Text.Json;
using static Json_Tests.JsonHelpers;

namespace Json_Tests
{

public class Class1
{
    public void Test()
    {
        var obj1 = new ClassToSerialize();
        var jsonStr = obj1.ToString();

        // if you have the class structure for the jsonStr (for example, if you have created the jsonStr yourself from your code):
        var obj2 = DeSerializeFromStrToObj<ClassToSerialize>(jsonStr);
        Console.WriteLine($"{nameof(obj2.Name)}: {obj2.Name}");

        // if you do not have the class structure for the jsonStr (forexample, jsonStr comes from a 3rd party service like the web):
        var obj3 = JsonSerializer.Deserialize<object>(jsonStr) as JsonElement?;
        var propName = nameof(obj1.Name);
        var propVal1 = obj3?.GetProperty("Name");// error prone
        Console.WriteLine($"{propName}: {propVal1}");
        JsonElement propVal2 = default;
        obj3?.TryGetProperty("Name", out propVal2);// error prone
        Console.WriteLine($"{propName}: {propVal2}");

        var obj4 = DeSerializeFromStrToDict(jsonStr);
        foreach (var pair in obj4)
            Console.WriteLine($"{pair.Key}: {pair.Value}");
    }
}

[Serializable]
public class ClassToSerialize
{
    // important: properties must have at least getters
    public string Name { get; } = "Paul";
    public string Surname{ get; set; } = "Efford";

    public override string ToString() => JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true });
}

public static class JsonHelpers
{
    /// <summary>
    /// to use if you do not have the class structure for the jsonStr (forexample, jsonStr comes from a 3rd party service like the web)
    /// </summary>
    public static Dictionary<string, string> DeSerializeFromStrToDict(string json)
    {
        try
        {
            return JsonSerializer.Deserialize<Dictionary<string, string>>(json);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return new Dictionary<string, string>(); // return empty
        }
    }

    /// <summary>
    /// to use if you have the class structure for the jsonStr (for example, if you have created the jsonStr yourself from your code)
    /// </summary>
    public static T DeSerializeFromStrToObj<T>(string json) // see this: https://json2csharp.com/#
    {
        try
        {
            var o = (T)Activator.CreateInstance(typeof(T));

            try
            {
                var jsonDict = JsonSerializer.Deserialize<Dictionary<string, string>>(json);

                var props = o.GetType().GetProperties();

                if (props == null || props.Length == 0)
                {
                    Console.WriteLine($"Error: properties from target class '{typeof(T)}' could not be read using reflection");
                    return default;
                }

                if (jsonDict.Count != props.Length)
                {
                    Console.WriteLine($"Error: number of json lines ({jsonDict.Count}) should be the same as number of properties ({props.Length})of our class '{typeof(T)}'");
                    return default;
                }

                foreach (var prop in props)
                {
                    if (prop == null)
                    {
                        Console.WriteLine($"Error: there was a prop='null' in our target class '{typeof(T)}'");
                        return default;
                    }

                    if (!jsonDict.ContainsKey(prop.Name))
                    {
                        Console.WriteLine($"Error: jsonStr does not refer to target class '{typeof(T)}'");
                        return default;
                    }

                    var value = jsonDict[prop.Name];
                    Type t = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                    object safeValue = value ?? Convert.ChangeType(value, t);
                    prop.SetValue(o, safeValue, null); // initialize property
                }
                return o;
            }
            catch (Exception e2)
            {
                Console.WriteLine(e2.Message);
                return o;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return default;
        }
    }
}
}
© www.soinside.com 2019 - 2024. All rights reserved.