如何为以下格式JSON创建c#类

时间:2015-11-06 17:06:27

标签: c# json

有人可以帮我构建以下格式JSON的类。

我已经尝试了http://json2csharp.com/工具。它不起作用,因为我的人员列表是动态的,即值123,124等没有预先定义。

{
  "people":
     {
        "123":"jack henry",
        "124":"john henry",
        "125":"jill henry",
        "215":"jim henry",
        ...
     }
}

3 个答案:

答案 0 :(得分:2)

Visual Studio>编辑>选择性粘贴>将JSON粘贴为类

public class Rootobject
{
    public People people { get; set; }
}

public class People
{
    public string _123 { get; set; }
    public string _124 { get; set; }
    public string _125 { get; set; }
    public string _215 { get; set; }
}

您已经得到了问题的答案。但是,查看示例JSON看起来实际上是在存储人员列表。如果是这种情况,您可以创建类似这样的类

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

public class People
{
    public List<Person> Persons { get; set; }
    //other properties
}

让您的JSON标准化为

{
  "Persons": [
    {
      "Id": 123,
      "Name": "Jack"
    },
    {
      "Id": 124,
      "Name": "John"
    }
  ]
}

哪些更有意义和可读性(通过代码和人工)。

答案 1 :(得分:2)

public class Root
{
     public Dictionary<string, string> people = new Dictionary<string,string>();
}

使用Json.NET

Root root = new Root();

root.people.Add("123", "jack henry");
//... Add more people

string json = JsonConvert.SerializeObject(root);

答案 2 :(得分:0)

来源:http://json2csharp.com/

public class People
{
    public string __invalid_name__123 { get; set; }
    public string __invalid_name__124 { get; set; }
    public string __invalid_name__125 { get; set; }
    public string __invalid_name__215 { get; set; }
}

public class RootObject
{
    public People people { get; set; }
}
相关问题