3

I would like to send Json to the server, and we do that with Newtonsoft's Json.NET1. The json may contain type information ("$type" = ...). This type info may point to an unknown type. Said object would typically be contained in a property of type object.


What I would like to do:

  • Convert the part of the unknown type to a JObject
  • Preserve somehow the type information, so I can send the same json back to the client at a later point as it was passed to the server.

What I've tried so far

  • By replacing the SerializationBinder on the JsonSerializer, I can force Json.NET to deserialize the json contained into a JObject. This is almost what I would like to have, alas the $type property is lost.

  • In the binder returning a type that points to an object that would work in harmony with a custom JsonConverter which would gobble up the offending object such that upon write it would faithfully recreate the json as it was encountered. However, when you hit the $type info, no converters will be called anymore, apparently we are then in a different branch of the json.NET code

  • One can handle a serialization error, try to read from the reader the offending part, then one could create a JOBject manually and annotate the type information.

1) More specific - the built of it that is contained in the RavenDB.Abstractions, but hopefully they have not diverged too much.

flq
  • 22,247
  • 8
  • 55
  • 77
  • This is an interesting problem. Can you show your code for the `SerializationBinder` and the `JsonConverter` that you tried, along with the custom object it uses? Also what do you mean by "when you hit the $type info, no converters will be called anymore"? – Brian Rogers Sep 07 '13 at 14:38
  • Did you disable TypeHandling? Couldn't you roll it yourself using a new Type property with `[JsonProperty("$type")]` and handle getting/setting yourself through the binder and converter? – kamranicus Dec 30 '15 at 15:06
  • Related question: https://stackoverflow.com/questions/69261839/json-net-handle-unknown-derived-types-when-using-typenamehandling – Brandon Sep 20 '21 at 23:31

0 Answers0