【发布时间】:2015-08-26 21:53:10
【问题描述】:
我有一个带有 JSON 对象数组的流,它们有两种不同的格式,但包含相同类型的数据,我想将这两种格式反序列化为相同的类型,因此我的视图不需要自定义逻辑两种格式的数据。目前我正在使用自定义 JsonConverter 处理此问题。
这是我的模型:
[JsonObject]
[JsonConverter(typeof(MyCommonObjectJsonConverter))]
public class MyCommonObject {
// some common fields, e.g.
public String Id { get; set; }
public string Text { get; set; }
}
这是我的自定义 JsonConverter:
public class MyCommonObjectJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// don't need to worry about serialization in this case, only
// reading data
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jObject = JObject.Load(reader);
MyCustomObject result;
if (IsFormatOne(jObject))
{
// the structure of the object matches the first format,
// so just deserialize it directly using the serializer
result = serializer.Deserialize<MyCustomObject>(reader);
}
else if (IsFormatTwo(jObject))
{
result = new MyCustomObject();
// initialize values from the JObject
// ...
}
else
{
throw new InvalidOperationException("Unknown format, cannot deserialize");
}
return result;
}
public override bool CanConvert(Type objectType)
{
return typeof(MyCustomObject).IsAssignableFrom(objectType);
}
// Definitions of IsFormatOne and IsFormatTwo
// ...
}
但是,当我反序列化第一种格式的对象时,我收到一条错误消息,指出它无法加载 JObject,因为 JsonReader 的 TokenType 为“EndToken”。我不确定为什么会这样,我加载的数据格式正确。关于我应该注意什么有什么建议吗?
【问题讨论】:
标签: c# .net serialization json.net