Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flattening nested JSON object in JSON.NET

Tags:

c#

json.net

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.

like image 452
vvondra Avatar asked Oct 20 '22 09:10

vvondra


1 Answers

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; }
}
like image 189
DLeh Avatar answered Nov 15 '22 04:11

DLeh