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/