假设我有一个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);
}
}
有什么办法解决吗?即,使Custom转换器将字符串作为输入,并在解析字符串后将其转换为对象?我能想到的最接近的东西是JsonStringEnumConverter,它接受一个字符串并将其转换为Enum。
答案 0 :(得分:0)
我知道这不是您要的,但是解决这个问题的一种方法可能是:
public class MyClass{
*OTHER PROPERTIES*
public string DurationField { get; set;}
private Duration _duration = null;
[JsonIgnore]
public Duration Duration {
get {
if (_duration == null) {
_duration = new Duration(this.DurationField);
}
return _duration;
}
}
}
在无法正确解析等情况下,您可以保留原始的字符串值,但还可以访问Duration
。