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

时间:2016-10-21 08:49:02

标签: c# json

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

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

1 个答案:

答案 0 :(得分:0)

首先,您需要将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; }
}

您可以使用JsonConvert.DeserializeObject<T>(string)内的JSON.Net轻松完成此任务 获得列表后,您可以通过PHASE GroupBy按PHASE对列表进行分组。代码是这样的:

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

现在你有了一个小组(定义为IENumerable<IGrouping<string,RootObject1>>),你需要一个foreach进入每个小组并填写正确的类(并按照我的类型顺序排列我没错)。
完成foreach循环后序列化RootObject,您将根据需要格式化json 只是一个提示:PhaseN应为assays,否则您将无法获得正确的结果。