c# - 如何使用 System.Text.Json 访问从字符串反序列化的动态对象的属性?

标签 c# .net asp.net-core .net-5

using System.Text.Json;
using System.Text.Json.Serialization;

public static dynamic StringToObject(string str) {
    dynamic JsonObjectFromString = JsonSerializer.Deserialize<dynamic>(str);
    System.Console.WriteLine(JsonObjectFromString) // this line show correct json object with a correct type
    System.Console.WriteLine(JsonObjectFromString["cookies"]) // this line will error
    return JsonObjectFromString;
}

基本上,当我尝试访问动态反序列化对象的任何属性时,我的程序会出错。有没有办法动态使用JsonSerializer.Deserialize

该字符串基本上来自httpbin。

{
  "cookies": {}
}

顺便说一句,NewtonSoft.Json 不会发生这种情况。

错误:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'System.Text.Json.JsonElement.this[int]' has some invalid arguments
         at CallSite.Target(Closure , CallSite , Object , String )
         at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
         at myNamespace.myClass.StringToObject() in D:\lesha\screener\src\StringToObject.cs:line 12
         at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()

最佳答案

通常,当尝试引用 json 字符串的特定元素而不反序列化为强类型对象时,您不希望完全反序列化该对象,因为您只使用数据的子集。在这些情况下,请使用JsonDocument.Parse API:

var json = "{\"cookies\": { \"id\": 1 } }";

var options = new JsonDocumentOptions { AllowTrailingCommas = true };

using var document = JsonDocument.Parse(json, options);
Console.WriteLine(document.RootElement.GetProperty("cookies"));

如果您绝对想使用动态,则无法检索部分结构,因为基础类型 JsonElement 不包含允许您遍历对象的运行时绑定(bind)器。因此,您有两个选择:可以将动态转换为 JsonElement,也可以直接反序列化为 JsonElement。这允许您使用 GetProperty 方法。

var str = "{\"cookies\": { \"id\": 1 } }";
var JsonObjectFromString = JsonSerializer.Deserialize<JsonElement>(str);
Console.WriteLine(JsonObjectFromString);
Console.WriteLine(((JsonElement)JsonObjectFromString).GetProperty("cookies"));

关于c# - 如何使用 System.Text.Json 访问从字符串反序列化的动态对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65635823/

相关文章:

c# - 打包 Visual C# Express 项目时的 SVN 文件夹

c# - 未知客户端或客户端未启用 Identity Server 4

c# - ASP.net Core中host和server的区别和联系

ubuntu - Asp.Net Core - 已达到 inotify 实例数量的配置用户限制 (128)

c# - 从 Grib2 天气文件 C# 中提取值?

c# - 使用多态性时重载方法的 ILDASM 代码

c# - 我怎样才能得到段落开头的首字母?

c# - DateTime.TryParseExact 与 "U"和 DateTimeStyles.AdjustToUniversal

c# - C# 中与 DateTime 对象的字符串连接 : why is my code legal?

.net - 是否有一个 .NET 类可以从 LDAP 中解析 CN= 字符串?