Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.NET: JsonCreationConverter working WriteJson implementation

From this answer I have class JsonCreationConverter<T> and some implementations for concrete types. But this abstract class misses the implementation of WriteJson method.

Over the internet I find the code:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    //use the default serialization - it works fine
    serializer.Serialize(writer, value);
}

But this code ends up with StackOverflowException as it calls itself all the time (of course). Other solutions were for concrete objects implementations with serializing all the values one by one. I really want to avoid it, just want to use default serialization, which is OK for me. Just to avoid calling my JsonConverter for serialization. I need it only for deserialization. Is it possible? How?

like image 910
Zoka Avatar asked Jul 07 '14 00:07

Zoka


People also ask

How does Newtonsoft JSON work?

Newtonsoft. Json uses reflection to get constructor parameters and then tries to find closest match by name of these constructor parameters to object's properties. It also checks type of property and parameters to match. If there is no match found, then default value will be passed to this parameterized constructor.

What does Jsonconvert DeserializeObject do?

DeserializeObject Method. Deserializes the JSON to a . NET object.

What is JsonConverter?

Converts an object to and from JSON. Newtonsoft.Json.


1 Answers

Try overriding the CanWrite property getter in the converter so that it returns false. This will prevent the converter from being used during serialization.

    public override bool CanWrite
    {
        get { return false; }
    }
like image 58
Brian Rogers Avatar answered Oct 04 '22 11:10

Brian Rogers