Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#中的对象定义符合JSON定义_C#_Json_Serialization_Json.net - Fatal编程技术网

C#中的对象定义符合JSON定义

C#中的对象定义符合JSON定义,c#,json,serialization,json.net,C#,Json,Serialization,Json.net,我有一个JSON定义: { "id": 1400, "types": { "type one": { "url": "http://www.example.com", "desc": "type one desc" }, "type two": { "url": "http://www.example.com", "desc": "type

我有一个JSON定义:

{
    "id": 1400,
    "types": {
        "type one": {
           "url": "http://www.example.com",
           "desc": "type one desc"
        },
        "type two": {
            "url": "http://www.example.com",
            "desc": "type two desc"
        }
    }
}
我需要创建一个C#类,当序列化该类时会生成上面的JSON

我遇到的问题是“第一类”和“第二类”。如果我的班级是这样的:

public class mytypes{

    public int id { get; set; }
    public List<mytype> types { get; set; }
}
数据来自一个数据库,这将生成一个“类型”数组,而不是一个“类型”对象,其中的对象具有描述作为定义(类型1,类型2)

如何更改类以在“类型”中生成“类型一”和“类型二”,而不是数组?

而不是使用:

public List<mytype> types { get; set; }

列表中是否有未知数量的“类型”?如果它总是相同的数字,你可以像你说的那样做JSON,但如果它真的是一个列表对象,列表将在JSON中显示“类型”的地方,所有内容都将被向下推一级。我没有发现这有什么帮助,最终手动序列化。是的,这个数字是未知的,因为它来自数据库,可能随时会更改。如果可能的话,我试图避免手动序列化。是的,我也试图避免,但是自动序列化不能做任何特殊的事情。它必须向您显示整个层次结构,因此它必须将列表作为对象包含在内,其中包含其他对象。下面建议的字典也是这样的。下面的Garath示例非常有用。如果你给密钥提供了密钥,那么它使用那些创建“类型1”、“类型2”等等。我会考虑部分手动序列化。谢谢Garath。我唯一不明白的是“第一类”、“第二类”是如何分配的?只要用正确的键将元素添加到字典中就行了。Liek this:types.Add(“typeone”,newmytype{url=”“,desc=“something”});
public List<mytype> types { get; set; }
public Dictionary<string,mytype> types { get; set; }