我有一个仅在反序列化时要使用的转换器。因此,我将CanWrite设置为false,这可以正常工作,并且所有Serializes都可以正常工作。然后,Json字符串包含一个对象图,其中包含一个SantaClauseCollection,其中包含一系列SantaClause项目和一个$ type指示它们是具体类型SantaClause。
但是,当它在反序列化时遇到SantaClaus集合时,它永远不会调用CanConvert(我有一个断点,看到SantaClausCollection,按F5键继续,然后在遇到SantaClaus集合中的某个项目时应再次达到断点,但事实并非如此。当涉及到SantaClaus项目时,它并没有尝试调用CanConvert。甚至没有为该项目调用CanConvert来检查我的转换器是否会处理它,而是尝试本身对其进行反序列化,因为该类没有默认构造函数,并且没有具有属性名称匹配约定的构造函数,所以该方法不起作用:
我知道为什么会收到此错误,但问题是它表明Json.net尝试对对象进行反序列化,而不是调用CanConvert来检查并查看我的转换器是否要处理反序列化。
为什么不为集合中的每个项目调用CanConvert?
我的转换器:
class SantaClaus2JsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(SantaClaus);
}
/// <summary>
/// Deserializes a SantaClaus as a SantaClausEx which has a matching constructor that allows it to deserialize naturally.
/// </summary>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return serializer.Deserialize<SantaClausEx>(reader);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanWrite
{
get
{
return false;//We only need this converter when reading.
}
}
}
SantaClausEx只是从SantaClaus继承而来,以添加具有重命名参数的构造函数来匹配属性:
class SantaClaus //a third party class I can't modify
{
string Name {get;set;}
public SantaClaus(string santaClauseName) { this.Name = santaClauseName }
}
class SantaClausEx:SantaClaus
{
//provide a constructor with param names matching property names
public SantaClausEx(string name) : base(name)
}
Json.net不能反序列化SantaClaus,但是可以反序列化SantaClauseEx。
我到处都使用该SantaClauseEx类,并且效果很好,但是我想创建一个转换器来自动执行此操作。
这就是Json集合的外观:
SantaClausCollection: [
{
$type: "SantaClaus, XMasClasses.NET20"
Name: "St. Bob"
},
{
$type: "SantaClaus, XMasClasses.NET20"
Name: "St. Jim"
}
]
最佳答案
我想您已将转换器添加到settings对象中的Converters
集合中。
我用转换器编写了简单的测试
public class SantaClausJsonTest
{
public SantaClausJsonTest()
{
Settings = new JsonSerializerSettings();
Settings.TypeNameHandling = TypeNameHandling.Objects;
Settings.Converters.Add(new SantaClaus2JsonConverter());
}
private JsonSerializerSettings Settings;
[Fact]
public void SerializeAndDeserialize()
{
var collection = new []
{
new SantaClaus("St. Bob"),
new SantaClaus("St. Jim"),
};
var serialized = JsonConvert.SerializeObject(collection, Settings);
Console.WriteLine(serialized);
Assert.False(string.IsNullOrEmpty(serialized));
var deserialized = JsonConvert.DeserializeObject<SantaClaus[]>(serialized, Settings);
Console.WriteLine(deserialized.GetType().ToString());
Assert.NotNull(deserialized);
Assert.True(deserialized.Any(a => a.Name == "St. Bob"));
Assert.True(deserialized.Any(a => a.Name == "St. Jim"));
}
}
public class SantaClaus
{
public SantaClaus(string santaClauseName)
{
Name = santaClauseName;
}
public string Name { get; private set; }
}
public class SantaClaus2JsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(SantaClaus);
}
/// <summary>
/// Deserializes a SantaClaus as a SantaClausEx which has a matching constructor that allows it to deserialize naturally.
/// </summary>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var name = string.Empty;
while (reader.Read())
{
if (reader.TokenType == JsonToken.String && reader.Path.EndsWith("Name"))
{
name = reader.Value as string;
}
if (reader.TokenType == JsonToken.EndObject)
{
break;
}
}
return Activator.CreateInstance(objectType, name);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotSupportedException();
}
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanWrite
{
get
{
return false;//We only need this converter when reading.
}
}
关于c# - JSON.Net不为收集项目调用CanConvert吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14887389/