0

Is there any way in Json.Net to tell it to serialize most types as normal, but to use a custom serializer I'll provide whenever it spots an object of type x?

Essentially the idea here is that AFAIK, if you want to use custom serialization for a type in Json.Net, you have to specify how that's done inside the type, eg. by implementing ISerializable or by using attributes. However if I don't have access to the type, I can't modify serialization for the type.

Instead I want to know if I can inject that information into the jsonConverter, so that it will know to use custom serialization for the type.

Hypothetically I want to do something like this:

class A 
{
    B B {get; set;}
}

class B
{
}

BSerializer : ISerilalizer<B>
{
     public string Serialize(B obj) => "This is a B"
}

...

JsonConverter.SerializeObject(new A{B = new B()}, new BSerializer()) 

And the result of this serialization would be

{
    "B" : "This is a B"
}

Now obviously this interface doesn't exist, but can I do something similiar using the existing APIs Json.Net provides?

Yair Halberstadt
  • 5,733
  • 28
  • 60
  • 2
    Implement a custom `JsonConverter`, return `CanConvert(Type objectType) => objectType == typeof(B)` and do your thing in `WriteJson()`? Then register that custom JsonConverter with the `SerializeObject` overload that allows that. – CodeCaster Dec 19 '18 at 12:13
  • Possible duplicate of [Json.Net - Error getting value from 'ScopeId' on 'System.Net.IPAddress'](https://stackoverflow.com/questions/18668617/json-net-error-getting-value-from-scopeid-on-system-net-ipaddress) – krillgar Dec 19 '18 at 12:14
  • While the question that I'm marking this as a duplicate of is highly specialized, the accepted answer goes over how to create the custom `JsonConverter` that you need, and it can easily be adapted for your specific use case. – krillgar Dec 19 '18 at 12:15
  • thanks @krillgar - that looks useful. I'll try it out once I get a chance – Yair Halberstadt Dec 19 '18 at 12:48

0 Answers0