尝试将动态对象中存储的 json 转换为 Dictionary 对象时出现运行时错误 - Microsoft.CSharp.RuntimeBinder.RuntimeBinderException

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

在 Blazor Server 中,我调用 Web 服务并将结果存储在动态对象中。我想将该动态对象转换为 Dictionary 对象,或者将其传递给方法,以便我可以将其写入文件。但是无论我尝试对对象做什么,除了将其转换为字符串之外,我都会收到运行时错误:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:Message =“System.Text.Json.JsonSerializer.Deserialize>(System.Text.Json.JsonDocument,System.Text.Json.JsonSerializerOptions)”的最佳重载方法匹配有一些无效争论

我的代码在控制台应用程序中运行良好,但是当我尝试在 Blazor 服务器中运行它时,出现运行时错误。

这是我的代码:

namespace BlazorWebAssembly.Server.Endpoints
{
    public static class CybsAuthEndpoint
    {
        static SaveAuthData saveAuthData = new SaveAuthData();
        private static string Id = string.Empty;
        public static async void MapCybsCall(this WebApplication app)
        {
            ICallForCybsAuth cybsAuth = new CallForCybsAuth();
            dynamic jsonObject = new ExpandoObject();
            jsonObject = cybsAuth.RunAsyncJson();

            var options = new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
            var jsonString = JsonSerializer.Serialize(jsonObject, options);
            Console.WriteLine(jsonString);

            //**** This is what throws the Runtime Error: 
            var dict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, string>>(jsonObject); 
            //****

            app.MapGet("/cybersource", () =>  Results.Ok(jsonObject));
        }
    }
}
c# json blazor-server-side system.text.json
1个回答
0
投票

尝试将

jsonString
声明为
var
,而不是
string

我有一个类似的案例,导致了同样的问题。背景:

  • .net 8
  • 目标操作系统无
  • 任何CPU
  • 控制台应用程序,下面的代码位于类库中
dynamic requestData = new
{
    model = options.Model ?? throw new Exception("GPT model is not configured."),
    messages = messages.ToArray(),
    temperature = options.Temperature,
    top_p = options.TopP,
    max_tokens = options.ResponseMaxTokenCount
};
if (options.RequireJson) requestData.response_format = new { type = "json_object" };

var json = JsonSerializer.Serialize(requestData, new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
var content = new StringContent(json, Encoding.UTF8, "application/json");

//**** This is what throws the Runtime Error: 
this.Log.WriteLine(LogDensity.LD_6_7, (LGID, 0x74EFC2),
    CL(json)
);
//****

异常看起来像:

---> Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'Core.Instrumentation.ILog.WriteLine(int, System.ValueTuple<ulong,ulong>, params object[])' has some invalid arguments
   at CallSite.Target(Closure, CallSite, ILog, Int32, ValueTuple`2, String, String, String, Object)
   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid7[T0,T1,T2,T3,T4,T5,T6](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6)

var json = JsonSerializer.Serialize...
更改为
string json = JsonSerializer.Serialize...
(var -> string) 可有效解决该错误。

我的猜测是,尽管 JsonSerializer.Serialize 的所有重载都被记录为返回

string
void
,但使用
var
以某种方式导致它返回
dynamic
- 可能是作为一种形式或优化或懒惰的评估,我不知道。

如果有人可以阐明这个主题,我将不胜感激,我似乎无法找到明确的解释。

© www.soinside.com 2019 - 2024. All rights reserved.