作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用一个 API,由于某种原因,它在应该使用 null 的地方使用了 false。我不知道如何正确反序列化它。我尝试创建一个自定义 JsonConverter 来解决此问题,但无法做到这一点。我想避免使用动态类型。我应该如何反序列化它?
这是默认响应。
{
"products": [
{
"id": 123456789,
"supplier": {
"id": 123456,
"title": "abc"
}
}
]
}
我正在反序列化如下。
public class Container
{
public Product[] products { get; set; }
}
public class Product
{
public ulong id { get; set; }
public Supplier supplier { get; set; }
}
public class Supplier
{
public ulong id { get; set; }
public string title { get; set; }
}
JsonSerializer.Deserialize<Container>(json)
这是当产品没有供应商时的响应。
{
"products": [
{
"id": 123456789,
"supplier": false
}
]
}
最佳答案
您可以为 supplier
属性创建自定义 JsonConverter
:
public class Product
{
public ulong id { get; set; }
[JsonConverter(typeof(SupplierConverter))]
public Supplier supplier { get; set; }
}
public class SupplierConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Boolean)
{
if ((bool)reader.Value == false)
return null;
}
return serializer.Deserialize(reader, objectType);
}
public override bool CanConvert(Type objectType)
{
return false;
}
}
更新:
如果您使用的是System.Text.Json
,您可以尝试以下自定义转换器:
public class SupplierConverter : JsonConverter<Supplier>
{
public override Supplier Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.False)
return null;
if (options.GetConverter(typeof(JsonElement)) is JsonConverter<JsonElement> converter)
{
var json = converter.Read(ref reader, typeToConvert, options).GetRawText();
return JsonSerializer.Deserialize<Supplier>(json);
}
throw new JsonException();
}
public override void Write(Utf8JsonWriter writer, Supplier value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
关于c# - 将 false 反序列化为 null (System.Text.Json),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60634410/
出于好奇,我尝试了一些原型(prototype)制作,但似乎只允许在第一个位置使用子例程的原型(prototype) &。 当我写作时 sub test (&$$) { do_somethin
我需要开发一个类似于 Android Play 商店应用程序或类似 this app 的应用程序.我阅读了很多教程,发现几乎每个教程都有与 this one 类似的例子。 . 我已经开始使用我的应用程
考虑一个表示“事件之间的时间”的列: (5, 40, 3, 6, 0, 9, 0, 4, 5, 18, 2, 4, 3, 2) 我想将这些分组到 30 个桶中,但桶会重置。期望的结果: (0, 1,
我是一名优秀的程序员,十分优秀!