使用C#和LINQ在json.net中创建树形结构

4
我看了这个问题和答案Create tree hierarchy in JSON with LINQ,它与我所需的非常接近。但是,由于我正在使用json.net,因此无法生成下面显示的嵌套数组。 Class.cs
    public class RootObject
    {
        public List<Attribute> test { get; set; }
    }
    public class Attribute
    {
        public string testKey { get; set; }
        public string start { get; set; }
        public string finish { get; set; }
        public string comment { get; set; }
        public string status { get; set; }
    }


    public class AttributeData
    {
        public Attribute AttributeDataOps()
        {
            ***Attribute DATA***
        }
    }

Program.cs

Attribute attribute = new Attribute();
AttributeData attributeData = new AttributeData();
string JSONresult = JsonConvert.SerializeObject(attribute);
string path = @"C:\file.json";

期望结果

{
    "tests" : [
        {
            "testKey" : "",
            "start" : "",
            "finish" : "",
            "comment" : "",
            "status" : ""
        }
    ]
}

当前结果

    {
        "testKey" : "",
        "start" : "",
        "finish" : "",
        "comment" : "",
        "status" : ""
    }
1个回答

4
您期望传递一个集合,但您传递了单个对象进行序列化。
var rootObject = new RootObject();
List<Attribute> attribute = new List<Attribute>();
rootObject.test = attribute;
string JSONresult = JsonConvert.SerializeObject(rootObject);

列表<属性>部分无法显示。我需要为此创建一个对象吗? - Kim
你需要为它增加价值。 - Eldho

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接