我似乎无法解决这个问题.我在同一问题上找到的所有其他问题都针对Newtonsoft.Json.

我使用外部提供的json API,该API返回字典.但如果它是空的,它们就会返回一个空数组:

有数据:

"booking/index": {
   "key": {
         data...
          }
}

没有数据:

"booking/index": []

因此System.json解串器失败,出现这个错误(这是可以理解的):

System.Text.Json.JsonException:JNON值无法转换为System.Collections.Generic.Dictionary ' 2[System.字符串,checkfront_reports.Models.Api. BookingIndexObj].路径:$ð ' booking/index ']|线路号:0|字节位置InLine:408.

这里是我进行的调用和数据模型供参考:

var bookingIndex = await httpClient.GetFromJsonAsync<BookingIndexObj>($"booking/index?start_date={startDate.ToString("yyyy-MM-dd")}&end_date={endDate.ToString("yyyy-MM-dd")}");

public class BookingIndexObj
{
    public BookingRequestObj Request { get; set; }

    [JsonPropertyName("booking/index")]
    public Dictionary<string, BookingIndexIndexObj> BookingIndex { get; set; }
}

public class BookingIndexIndexObj
{
    public string? Code { get; set; }

    [JsonPropertyName("status_id")]
    public string? StatusId { get; set; }
}

public class BookingRequestObj
{
    public int Page { get; set; }

    public int Pages { get; set; }
}

推荐答案

I am not sure at all if this is how we are supposed to do this,但至少它有效:

(请注意,我简化了示例)

using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        var emptyJson = 
            """
{
    "values": []
}
""";
    
        var nonEmptyJson = 
            """
{
    "values": {
        "key1": "value1",
        "key2": "value2"
    }
}
""";
        
        var emptyResult = JsonSerializer.Deserialize<Model>(emptyJson);
        var nonEmptyResult = JsonSerializer.Deserialize<Model>(nonEmptyJson);
        
        emptyResult.Dump();
        nonEmptyResult.Dump();
    }
}

public class Model
{
    [JsonPropertyName("values")]
    [JsonConverter(typeof(MySpecialConverter))]
    public Dictionary<string,string> Values {get;set;} = new();
}

public class MySpecialConverter : JsonConverter<Dictionary<string,string>>
{
// Omitted writer for brevity. 
    public override void Write(Utf8JsonWriter writer,
            Dictionary<string,string> dictionaryValue,
            JsonSerializerOptions options) => throw new NotSupportedException();
            
    public override Dictionary<string,string> Read(ref Utf8JsonReader reader,
            Type typeToConvert,
            JsonSerializerOptions options)
            {
// Check for '"booking/index": []' - case:
                if (reader.TokenType == JsonTokenType.StartArray)
                {
                  reader.Read();
                  return new Dictionary<string,string>();
                }
// Otherwise pass-through to default converter.
                var converter = (JsonConverter<Dictionary<string,string>>)options.GetConverter(typeof(Dictionary<string,string>));
                return converter.Read(ref reader, typeToConvert, options);
            }
}

= 小提琴 : https://dotnetfiddle.net/J6NbVE>

For your reference:
I based this upon this article: How to write custom converters for JSON serialization (marshalling) in .NET

Csharp相关问答推荐

如何基于记录数组,在一次拍摄中更新单个MongoDB集合的多个记录中的子嵌入文档?

如何修改扩展方法以在C#中的DataTable转换中包括/排除特定列?

System.Text.Json:反序列化返回为空数组的字典时出错

将多个enum值传递给MAUI中的转换器参数的XML语法是什么?

如何使嵌套for-loop更高效?

程序集.加载从exe的异常

如何在Cosmos SDK中控制超时、重试和重试之间的延迟?

正在try 从Blazor中的API读取JSON

在使用StringBuilder时,如何根据 colored颜色 设置为richTextBox中的特定行着色?

为什么Docker中没有转发该端口?

Azure Functions v4中的Serilog控制台主题

在集成测试中可以在模拟InMemory数据库中设定数据种子

MSI无法将快捷方式添加到启动文件夹

当我try 在与XAMP的MySQL服务器连接的ASP.NET核心应用程序中添加迁移时出现错误

实体框架-IsRequired()与OnDelete()

毛伊岛.NET 8图片不再适合按钮

在C#/ASP.NET Core 7中,什么可能导致POST请求作为GET请求发送

如何读取TagHelper属性的文本值?

最小API定义的Swagger标头参数

在使用xUnit和Mock执行单元测试时,控制器ViewResult返回空的Model集合