5

I have a simple JSON like this:

{
    "id": 123,
    "name": "BaseName",
    "variation": { "name": "VariationName" }
}

Is there a simple way to map it with JSON.NET deserialization to:

class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string VariationName { get; set; }
}

I can probably do it with a custom converter, but I hoped there would be a simpler way by annotating the class with attributes which would give instructions to deserialize the variation object just using the one property.

vvondra
  • 3,022
  • 1
  • 21
  • 34
  • A custom converter might be the best route here – Andrew Whitaker Jun 18 '15 at 13:58
  • You could create a custom converter that uses the attributes you propose. :) – Mattias Nordqvist Jun 18 '15 at 13:59
  • See here https://stackoverflow.com/questions/30222921/deserializing-json-to-flattened-class or here http://stackoverflow.com/questions/30175911/can-i-serialize-nested-properties-to-my-class-in-one-operation-with-json-net – dbc Jun 18 '15 at 21:36

1 Answers1

3

You could set up a class for variation and make VariationName a get-only property

class Product
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Variation variation { get; set; }
    public string VariationName { get { return variation.VariationName; } }
}

class variation 
{
    public string name { get; set; }
}
DLeh
  • 23,806
  • 16
  • 84
  • 128
  • 1
    My example is a bit simplified, so it's not that elegant but this will probably the simplest way to go. I was curious if there is any trick I am missing. I'll see if there's any other suggestion and accept this. – vvondra Jun 18 '15 at 14:00