2015-11-06 60 views
-5

有人可以帮我构建JSON格式的类。如何创建以下格式JSON的c#类

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

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

http://json2csharp.com/ – Nasreddine

+4

的可能的复制[如何转换JSON对象为自定义C#对象?(http://stackoverflow.com/questions/2246694/how-to-convert-json-object-to-custom-c-sharp-object) – MethodMan

+0

我在你的名字中看到一个重复的条目。您用两个不同的值将名称“124”列出两次。您可能会意外错误地设置了此格式。 {“people”:[ {“ID”:“123”,“Name”:“jack henry”}, {“ID”:“124”,“Name”:“john henry”}, {additional objects} ]}' – Grungondola

回答

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); 
+0

谢谢。这是有效的。 –

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

为什么要投票?这与Arghya拥有两张赞成票的答案完全相同。 –

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" 
    } 
    ] 
} 

,这将是更加有意义和可读性(代码和人力)。

+0

这不是我想要的... 123,124,125,215它们不是静态的......我们如何创建一个动态类属性..... –

+1

那么,在你的问题中提到的是哪里? –

+0

我的错误我现在更新了我的问题。 –