如何使用cs类将平面文件转换为嵌套JSON

本文关键字:转换 嵌套 JSON 平面文件 何使用 cs | 更新日期: 2023-09-27 18:14:04

我已经从下面的数据表创建了一个JSON字符串,并从所需的嵌套输出生成了类。我需要帮助与c sharp代码后面转换字符串到一个嵌套的对象。我需要为此创建一个定制的序列化器吗?有更好的方法吗?

string = [{"name":"example1", "priority" : "high", "PHASE": "phase1","id" :1001, "type": "glove"},
{"name":"example1", "priority" : "high", "PHASE": "phase1","id" :1002, "type": "shoe"},
{"name":"example1", "priority" : "high", "PHASE": "phase1","id" :1003, "type": "sock"},
{"name":"example1", "priority" : "high", "PHASE": "phase2","id" :1005, "type": "large"},
{"name":"example1", "priority" : "high", "PHASE": "phase2","id" :1006, "type": "medium"},
{"name":"example1", "priority" : "high", "PHASE": "phase2","id" :1007, "type": "small"},
{"name":"example1", "priority" : "high", "PHASE": "phase3","id" :1008, "type": "ladies"},
{"name":"example1", "priority" : "high", "PHASE": "phase3","id" :1009, "type": "gents"}];

desired_output = {
"NAME": "example1",
"PRIORITY" : "high",
"PHASE":
          {
            "phase1":
                      [
                       { "id": "1001", "type": "glove" },
               { "id": "1002", "type": "shoe" },
               { "id": "1003", "type": "sock",
"ph2":
           {
              "phase2" :
                      [
                       { "id": "1005", "type": "large" },
               { "id": "1006", "type": "medium" },
               { "id": "1007", "type": "small", 
"ph3":
           {
             "phase3": 
                        [
                       { "id": "1008", "type": "ladies" },
               { "id": "1009", "type": "gents" }
]}
}
]}
}
]
}
}

public class Phase3
{
    public string id { get; set; }
    public string type { get; set; }
}
public class Ph3
{
    public List<Phase3> phase3 { get; set; }
}
public class Phase2
{
    public string id { get; set; }
    public string type { get; set; }
    public Ph3 ph3 { get; set; }
}
public class Ph2
{
    public List<Phase2> phase2 { get; set; }
}
public class Phase1
{
    public string id { get; set; }
    public string type { get; set; }
    public Ph2 ph2 { get; set; }
}
public class PHASE
{
    public List<Phase1> phase1 { get; set; }
}
public class RootObject
{
    public string NAME { get; set; }
    public string PRIORITY { get; set; }
    public PHASE PHASE { get; set; }
}

如何使用cs类将平面文件转换为嵌套JSON

首先,您需要将json解析为List<RootObject1>,其中RootObject1定义为:

public class RootObject1
{
    public string name { get; set; }
    public string priority { get; set; }
    public string PHASE { get; set; }
    public int id { get; set; }
    public string type { get; set; }
}

JSON.Net中使用JsonConvert.DeserializeObject<T>(string)可以很容易地完成此任务。
一旦你有了列表,你可以通过GroupBy按阶段对列表进行分组。代码是这样的:

var groups = myList.GroupBy(x => x.PHASE);

现在你有组(定义为IENumerable<IGrouping<string,RootObject1>>),你需要一个foreach去每个组,并填写适当的类(并按类型排序,我没有错)。
一旦你完成了foreach循环,序列化你的RootObject,你就会得到你想要的json格式。
只是一个提示:PhaseN应该是assays,否则你将得不到正确的结果。