使用 JsonSerialize.DeserializeAsync
反序列化和自定义转换器,例如
public class MyStringJsonConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.GetString();
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
在这里我会得到所有 string
属性,这还可以,但是有什么方法可以检查给定值的属性名称,例如像这样,在哪里只处理 Body
属性(property):class MyMailContent
{
public string Name { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
public class MyStringJsonConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.PropertyName.Equals("Body"))
{
var s = reader.GetString();
//do some process with the string value
return s;
}
return reader.GetString();
}
}
或者有没有其他方法可以挑选出给定的属性(property)?请注意,我正在寻找使用
System.Text.Json
的解决方案.
最佳答案
System.Text.Json 不制作父属性名称,或者更一般的 path到当前值,内部可用 JsonConverter<T>.Read()
.此信息在内部进行跟踪 -- 在 ReadStack.JsonPath()
中-- 但是 ReadStack
是内部的,永远不会传递给应用程序代码。
但是,如 Registration sample - [JsonConverter] on a property 中所述,您可以申请您的MyStringJsonConverter
直接到 public string Body { get; set; }
通过使用 JsonConverterAttribute
:
class MyMailContent
{
public string Name { get; set; }
public string Subject { get; set; }
[JsonConverter(typeof(MyStringJsonConverter))]
public string Body { get; set; }
}
通过这样做,MyStringJsonConverter.Read()
和 .Write()
只会为 MyMailContent.Body
触发.即使你有一些整体JsonConverter<string>
在 JsonSerializerOptions.Converters
, 应用于属性的转换器将 take precedence :During serialization or deserialization, a converter is chosen for each JSON element in the following order, listed from highest priority to lowest:
[JsonConverter]
applied to a property.- A converter added to the
Converters
collection.[JsonConverter]
applied to a custom value type or POCO.
(请注意,这与 Newtonsoft 部分不同,其中应用于类型的转换器取代了设置中的转换器。)
关于c# - System.Text.Json:在自定义转换器中获取属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67659071/