0

If I have an object

public class Car
{
  public int Speed = 0;
}

and then serialize this as following:

var str = JsonConvert.SerializeObject(new Car(), new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });

I would get an JSON looking something like this:

{
"$type":"Car",
"Speed": 0
}

I would like to upload this JSON-data to for example Firebase Realtime Database, but it doesn't allow the usage of '$' in keys.

How would I best replace "$type" with something custom like "typeKey"? But still be able to convert the JSON-data into objects when deserializing and make it use type information from the new key ("typeKey" instead of it looking for "$type")?

Whyser
  • 2,187
  • 2
  • 20
  • 40
  • 1
    Renaming the `$type` property is not implemented, see [JSON.Net - Change $type field to another name?](https://stackoverflow.com/q/9490345/3744182) for confirmation and workarounds. You will have to pre-process & post-process your JSON, e.g. by loading into a temporary `JToken` hierarchy or by subclassing `JsonTextReader` and `JsonTextWriter`. In fact I think your question is a duplicate, agree? – dbc Aug 09 '22 at 15:34
  • See also [Customizing the TypeNameHandling value name in the output JSON](https://stackoverflow.com/q/67935577) (not answered) and [JSON.NET Custom TypeHandling](https://stackoverflow.com/q/35743027) (whose accepted answer suggests using a custom `JsonConverter` along the lines of [Deserializing polymorphic json classes without type information using json.net](http://stackoverflow.com/q/19307752/10263) instead of `TypeNameHandling`.) – dbc Aug 09 '22 at 15:36
  • Thanks @dbc ! Thought I did a thorough search, but it seems I missed some! I had already checkout out all of the ones you mentioned except for the most obvious one ( "JSON.Net - Change $type field to another name?") – Whyser Aug 10 '22 at 11:36

0 Answers0