C#属性值作为Json键名

时间:2018-11-27 20:07:08

标签: c# json json.net

我有这样的杰森:

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

反序列化时,我需要以下类结构

    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; }
    }

这意味着我需要创建特定的类,例如 Bruce Clark 等。是否可以反序列化此Json,而不是单独的Bruce,Clark等,我只是这样的一个人班

    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; }
    }

使JSON变为:

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

1 个答案:

答案 0 :(得分:2)

您的Json描述了一个对象,该对象具有一个名为Result的单一属性,即Dictionary<string, Person>

所以您的课程只需要看起来像是

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; }
}