c# - 使用 C# 使用 LINQ 在 json.net 中创建树层次结构

标签 c# linq json.net

我看了这个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" : ""
    }

最佳答案

您期待一个集合,但您传递了一个要序列化的对象。

var rootObject = new RootObject();
List<Attribute> attribute = new List<Attribute>();
rootObject.test = attribute;
string JSONresult = JsonConvert.SerializeObject(rootObject);

关于c# - 使用 C# 使用 LINQ 在 json.net 中创建树层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52870240/

相关文章:

c# - 计算价格方法在 Visual Studio 中不起作用

c# - MyApp.vshost.exe 应该与 MyApp.exe 一起分发吗?

c# - 编写谓词以使用 Entity Framework 搜索存储库时出现问题(相当于在 SQL 中使用 Join)

c# - 如何在不将转换器传递给 DeserializeObject 的情况下反序列化抽象项列表?

c# - WebClient:忽略 HTTP 500

c# - 使用单选按钮

c# - Linq-to-Entities 动态排序

c# - 如何在 linq 中获取数据库和本地序列之间的笛卡尔积?

asp.net-mvc - 如何将 XML 作为 POST 传递给 ASP MVC .NET 中的 ActionResult

C# JsonConvertDeserialization 返回空值