在反序列化对象数组(例如JsonConvert.DeserializeObject<Model[]>
(时,有没有办法在一个额外的属性中包含模型的完整JSON?
例如,如果我的JSON是:
[{"a":1,"b":2},{"a":3,"b":4}]
我的模型类是:
class Model
{
public string A { get; set; }
public string B { get; set; }
public string FullJson { get; set; }
}
在反序列化之后,FullJson
将包含用于阵列中第一个模型的{"a":1,"b":2}
和用于第二个的{"a":3,"b":4}
。有办法做到这一点吗?
要做到这一点,您需要为Model
类制作一个自定义JsonConverter
,如下所示:
class ModelConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Model);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
Model model = new Model();
serializer.Populate(jo.CreateReader(), model);
model.FullJson = jo.ToString(Formatting.None);
return model;
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
然后,在Model
类中添加一个[JsonConverter]
属性,就可以开始了:
[JsonConverter(typeof(ModelConverter))]
class Model
{
...
}
以下是一个工作演示:https://dotnetfiddle.net/hD5WqJ