Why JsonConverter.WriteJson() never gets called, although JsonConverter.ReadJson() does get called?

不羁的心 提交于 2019-12-25 04:09:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!