1

When using JSON.NET TypeHandling for json deserialization, is there a way to customize what property name it uses for type and what name is used to refer to which class?

I'm using an external api I can't control which returns json of this style.

[{
  "type": "comment",
  "message": "This is a comment",
  "user": "Mike"
 },
 {
  "type": "like",
  "user": "Matt"
 }]

Instead of "$type" is there a way to tell JSON.NET to look at "type"? Seems like there also should be a "TypeName" property on JsonObject because its currently looking for a fully qualified C# class name.

This question is strictly referring to the TypeHandling feature: http://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm

MrMagee
  • 95
  • 7
  • You will need to make a JsonConverter to handle this. See [Deserializing polymorphic json classes without type information using json.net](http://stackoverflow.com/q/19307752/10263) – Brian Rogers Mar 02 '16 at 15:41
  • Yeah, it seems like that must be the only solution currently. TypeHandling actually seems like it would work perfect here with a few more supported hooks. – MrMagee Mar 04 '16 at 03:41

2 Answers2

1

This type of customization to TypeHandling in JSON.NET does not exist yet. I have taken @BrianRogers advise and used JsonConverters given his advise below.

"You will need to make a JsonConverter to handle this. See Deserializing polymorphic json classes without type information using json.net – Brian Rogers Mar 2 at 15:41"

MrMagee
  • 95
  • 7
  • For confirmation that renaming the `$type` property is not implemented, see [JSON.Net - Change $type field to another name?](https://stackoverflow.com/q/9490345/3744182). – dbc Aug 09 '22 at 15:29
-1

You can use JsonProperty attribute to name the property used in the json.

The JsonProperty attribute should be used like this :

public class RootObject
{
      [JsonProperty(PropertyName = "type")] // It looks for 'type' name in json and set value in MyType property
      public string MyType{ get; set;}
}
Akash KC
  • 16,057
  • 6
  • 39
  • 59
  • This doesn't refer to TypeHandling. TypeHandling has to do with Inheritance and choosing which Class to use for deserialization based on the value of a json property. http://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm – MrMagee Mar 02 '16 at 09:48
  • I thought, you want to have proper property name for the json property. I am not familiar with json.net inheritance typehanding – Akash KC Mar 02 '16 at 09:57
  • Quick glance at documentation, it seems that you can still use JsonProperty attibute with TypeNameHandling.Auto parameter – Akash KC Mar 02 '16 at 10:16
  • That property only dictates what it attempts to look up with the "$type" property. Even so, AUTO doesn't automatically figure out your internal mapping to class unless you have different properties I believe. – MrMagee Mar 02 '16 at 11:39