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;
}
Basically when I try to access any property of dynamically deserialized object, my program errors. Is there any way to use JsonSerializer.Deserialize
dynamically?
The string is basically from httpbin.
{
"cookies": {}
}
Btw this doesn't happen with NewtonSoft.Json.
Error:
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:leshascreenersrcStringToObject.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()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…