我似乎无法解决这个问题。我能找到的与同一问题有关的所有其他问题都是针对 Newtonsoft.Json 的。
我使用外部提供的 json API,它返回一个字典。但如果它是空的,它们会返回一个空数组:
有数据:
"booking/index": {
"key": {
data...
}
}
没有数据:
"booking/index": []
因此 System.json 反序列化器失败并出现此错误(这是可以理解的):
System.Text.Json.JsonException:JSON 值无法转换为 System.Collections.Generic.Dictionary`2[System.String,checkfront_reports.Models.Api.BookingIndexIndexObj]。路径:$['预订/索引'] |行号: 0 |字节位置内联: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; }
}
我完全不确定这是否是我们应该如何这样做,但至少它有效:
(请注意,我简化了示例)
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
供您参考:
我基于这篇文章:如何在 .NET 中编写用于 JSON 序列化(编组)的自定义转换器