Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use default serialization in a custom JsonConverter

Tags:

json

json.net

I have a complex object graph that I am serializing/deserializing with Json.NET. Some of the objects derive from an abstract class, so in order for the deserialization to work properly, I needed to create a custom JsonConverter. Its only role is to select the appropriate concrete implementation of the abstract class at deserialization-time and allow Json.NET to continue on its way.

My problem comes when I want to serialize. I don't need to do anything custom at all. I want to get exactly the same behavior as I would get using JsonConvert.SerializeObject with no custom JsonConverter.

However, since I'm using the custom JsonConverter class for my deserialization needs, I'm forced to supply a WriteJson implementation. Since WriteJson is abstract, I can't just call base.WriteJson, but I want to do essentially that. So my question is, what do I put in that method to get the plain-Jane, default behavior? In other words:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {     // What goes here to get default processing? } 
like image 783
Brian Rak Avatar asked Apr 13 '15 23:04

Brian Rak


People also ask

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.

What is Jsonconvert DeserializeObject?

DeserializeObject(String, Type,JsonConverter[]) Deserializes the JSON to the specified . NET type using a collection of JsonConverter. DeserializeObject(String, Type, JsonSerializerSettings) Deserializes the JSON to the specified .

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.


1 Answers

In your custom JsonConverter, override CanWrite and return false:

public override bool CanWrite { get { return false; } }  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {     throw new NotImplementedException(); } 

Then you can just throw an exception from WriteJson, since it won't get called.

(Similarly, to get default behavior during deserialization, override CanRead and return false.)

Note that the same approach can be used for JsonConverter<T> (introduced in Json.NET 11.0.1) since it is just a subclass of JsonConverter that introduces type-safe versions of ReadJson() and WriteJson().

like image 70
dbc Avatar answered Sep 29 '22 10:09

dbc