anitacynax
anitacynax

Reputation: 255

C# object representation of JSON string

I have the following JSON string:

{
    "region" : { 
        "center" : {
            "title" : "Center Region"
        },
        "east" : {
            "title" : "East Region - Form"
        }
    },
    "buttons" : {
        "save" : "Save"
    },
    "fields" : {
        "labels" : {
            "firstName" : "First Name",
            "lastName" : "Last Name",
            "chooseLocale" : "Choose Your Locale"
        }
    }
}

I was wondering whether this (see below) is the correct representation of the JSON string in C#:

public class Region 
{
    public Region() { }
}

public class Center : Region
{
    public Center() { }
    public string title { get; set; }
}

public class East : Region
{
    public East() { }
    public string title { get; set; }
}

public class Buttons
{
    public Buttons() { }
    public string save { get; set; }
}

public class Fields
{
    public Fields() { }
}

public class Labels : Fields
{
    public Labels() { }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string chooseLocale { get; set; }
}

I need the correct object representation which I can then serialize using JsonConvert.SerializeObject(object); in order to produce the JSON string above.

Upvotes: 0

Views: 214

Answers (2)

Sam Leach
Sam Leach

Reputation: 12956

Why are you using inheritance?

Your Json describes has a relationships, not is a relationships

The hierarchy goes:

region has center, east

buttons has save

fields has labels

labels has firstName, lastName, chooseLocale

Bold are root

Upvotes: 0

Yousuf
Yousuf

Reputation: 3275

Try this

public class Center
{
    public string title { get; set; }
}

public class East
{
    public string title { get; set; }
}

public class Region
{
    public Center center { get; set; }
    public East east { get; set; }
}

public class Buttons
{
    public string save { get; set; }
}

public class Labels
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string chooseLocale { get; set; }
}

public class Fields
{
    public Labels labels { get; set; }
}

public class RootObject
{
    public Region region { get; set; }
    public Buttons buttons { get; set; }
    public Fields fields { get; set; }
}

Upvotes: 1

Related Questions