问题
Why my custom JsonConverter.WriteJson() method doesn't get called ?
class MyType{
[JsonConverter(typeof(DocumentXamlDeserializer))]
public string GuiData { get; set; }
public string SimpleString;
}
Although the ReadJson
does get called:
public class DocumentXamlDeserializer : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(Gui.Handler.SerializeData());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var xaml = reader.Value as string;
Gui.Handler.DeserializeData(xaml);
return xaml;
}
public override bool CanConvert(Type objectType) { return typeof(string).IsAssignableFrom(objectType); }
}
The serialization call: JsonConvert.SerializeObject(dataModel, Formatting.Indented);
The deserialization call: JsonConvert.DeserializeObject<Model>(raw);
回答1:
Apparently this is because GuiData
is null... I guess I could specify:
TypeNameHandling = TypeNameHandling.Objects
But I want to serialize only GuiData
even if it's null (I set its value during serialization), without serializing all null-properties... well, if I don't find better way, I guess I'd have to suffice with it...
来源:https://stackoverflow.com/questions/16759441/why-jsonconverter-writejson-never-gets-called-although-jsonconverter-readjson