0

I have an object model that includes a collection of shapes - IShape. Various things implement this, like Rectangle, Circle etc.

If I define a json file for this like:

    "shapes": [
    {
      "shapeName": "Rectangle",
      "origin": {
        "x": 50,
        "y": 50
      },
      "height": 20,
      "width": 20,
      },
      "zOrder": 0
    },
    {
      "shapeName": "Circle",
      "origin": {
        "x": 50,
        "y": 50
      },
      "radius": 200,
      "zOrder": 0
    }
  ]

Using Json.Net I cant figure out how to create a custom converter for this.

Also, I dont really want to put attributes on my model classes...

Has anyone done something like this? Maybe I should really use XML... (sad).

Thanks

Jonesie
  • 6,997
  • 10
  • 48
  • 66
  • Oh, I just discovered TypeNameHandling. Investigating... – Jonesie Oct 27 '17 at 00:53
  • Using the `TypeNameHandling` setting is the easiest way to make it work. If you want an example of how to make a custom converter for this situation, see [this answer](https://stackoverflow.com/a/28523100/10263)-- it's pretty much the exact same scenario as you're describing. – Brian Rogers Oct 27 '17 at 04:05
  • See also [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/10263) – Brian Rogers Oct 27 '17 at 04:16

1 Answers1

0

Thanks for the links. In the end I found SerializationBinder which works ok, except I have $type in the serialized json in addition to my own "shapeName" property. The link above from Brian Rogers seems a better solution so I'll try that too.

Jonesie
  • 6,997
  • 10
  • 48
  • 66