假设我有一个 MyClass 类型的对象,它被序列化为 Json,如下所示:
{"DurationField":"3 Months", *OtherProperties*}
我想将此 Json 反序列化为以下类:
public class MyClass{
*OTHER PROPERTIES*
public Duration DurationField{ get; set;}
}
public class Duration{
public Duration()
// Constructor that takes a string, parses it and sets Units and N
public Duration(string strValue){
Duration duration = Duration.Parse(strValue)
N = duration.N;
Units = duration.Units;
}
// private method that takes a string and returns a Duration
private Duration Parse(string str){
...
}
// Enum field to represent units of time, like day/month/year
public TimeUnits Units{ get; set;}
// Number of units of time
public int N{ get; set;}
}
我试图实现一个自定义的 JsonConverter(如下),只是意识到它只能在“DurationField”的子节点上工作,这意味着我必须让它序列化为“DurationField”:{“Value”:“ 3 个月”} 或类似的东西。
public sealed class DurationConverter : JsonConverter<Duration>
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Duration));
}
public override Duration Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// Load the JSON for the Result into a JObject
JObject jo = JObject.Parse(reader.GetString());
// Read the properties which will be used as constructor parameters
string durationString = (string)jo["DurationField"];
// Construct the Result object using the non-default constructor
Duration result = new Duration(tenorString);
// (If anything else needs to be populated on the result object, do that here)
// Return the result
return result;
}
public override void Write(Utf8JsonWriter writer, Duration value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value, options);
}
}
有没有办法解决?即,让自定义转换器以字符串为输入,解析字符串后转换为对象?我能想到的最接近的东西是 JsonStringEnumConverter,它接受一个字符串并将其转换为一个 Enum。