cyboashu
cyboashu

Reputation: 10433

C# property value as Json Key Name

I have Json like this:

  {
  "Result": {
    "Bruce": {
      "City": "Gotham",
      "Age": 43
    },
    "Clark": {
      "City": "Metro",
      "Age": 43
    }
  }
}

When I deserialize it, I need the following class structure

    public class Clark
    {
        public string City { get; set; }
        public int Age { get; set; }
    }

    public class Bruce
    {
        public string City { get; set; }
        public int Age { get; set; }
    }

    public class Result
    {
        public Bruce Bruce { get; set; }
        public Clark Clark { get; set; }

    }

    public class RootObject
    {
        public Result Result { get; set; }
    }

That means I need to create specific classes as Bruce,Clark etc. Is it possible to deserialize this Json where instead of seperate Bruce, Clark etc, I have just one Person Class like this

    public class Person
    {
        public string Name { get; set; }
        public string City { get; set; }

        public int Age { get; set; }
    }
    public class Result
    {           
        public List<Person> Persons { get; set; }
    }

    public class RootObject
    {
        public Result Result { get; set; }
    }

so that the JSON becomes like :

{
  "Result": {
    "Persons": [
      {
        "Name": "Bruce",
        "City": "Gotham",
        "Age": 43
      },
      {
        "Name": "Clark",
        "City": "Metro",
        "Age": 43
      }
    ]
  }
}

Upvotes: 2

Views: 827

Answers (1)

maccettura
maccettura

Reputation: 10818

Your Json describes an object with a single property called Result, that is a Dictionary<string, Person>.

So your class(es) just need to look like is:

public class Person
{
    public string Name { get; set; }
    public string City { get; set; }
    public int Age { get; set; }
}

public class RootObject
{
    public Dictionary<string, Person> Result { get; set; }
}

Upvotes: 4

Related Questions