【发布时间】:2021-04-27 23:48:38
【问题描述】:
将代码从 newtonsoft json 迁移到 system.text.json 时
我需要将所有可为空的字符串呈现为空字符串。
我写了以下转换器,但所有空字符串值仍然呈现为空。
对于空字符串值,不会调用 Write 方法。断点永远不会被击中。
public class EmptyStringConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> Convert.ToString(reader.GetString(), CultureInfo.CurrentCulture);
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
if (writer == null)
throw new ArgumentNullException(nameof(writer));
writer.WriteStringValue(value ?? "");
}
}
启动代码
services.AddControllers()
.AddJsonOptions(option =>
{
option.JsonSerializerOptions.Converters.Add(new EmptyStringConverter());
});
控制台示例
class Program
{
static void Main(string[] args)
{
var jsonSerializerOptions = new JsonSerializerOptions();
jsonSerializerOptions.Converters.Add(new EmptyStringConverter());
var json = JsonSerializer.Serialize(new Model() { FirstName = null }, jsonSerializerOptions);
}
}
public class EmptyStringConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> Convert.ToString(reader.GetString(), CultureInfo.CurrentCulture);
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
if (writer == null)
throw new ArgumentNullException(nameof(writer));
writer.WriteStringValue(value ?? "");
}
}
public class Model
{
public string FirstName { get; set; }
}
【问题讨论】:
-
这似乎是设计意图。在
System.Text.Json.JsonPropertyInfoNotNullable<T1, T2, T3, T4>.OnWrite(WriteStackFrame& current, Utf8JsonWriter writer)中,如果value == null,则写入null并且不调用自定义转换器。 -
这与 Json.NET 一致,它也从不使用 null 调用
JsonConverter.WriteJson(),请参阅 How to force JsonConverter.WriteJson() to be called for a null value。但是,使用 Json.NET,您可以使用自定义合同解析器将空值替换为默认值,请参阅 Json Convert empty string instead of null。 -
但很遗憾,您不能在
System.Text.Json中这样做。System.Text.Json中的等效类型 --JsonClassInfo和JsonPropertyInfo-- 是 internal。有一个开放的增强功能Equivalent of DefaultContractResolver in System.Text.Json #42001 要求公开等效。 -
我应该这样回答吗?
-
是的,这可以标记为答案。
标签: c# .net-core system.text.json