从C#模型创建嵌套的JSON对象 [英] Create a nested json object from c# model

查看:453
本文介绍了从C#模型创建嵌套的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的json:

[
   {
      "ChangeFlowsFromParent":"false",
      "ChangeFlowsToParent":"true",
      "StreamType":"mainine",
      "streamName":"ArgOS_2_0",
      "Parent":"none",
      "Compliance":"Released",
      "children":[
         {
            "ChangeFlowsFromParent":"true",
            "ChangeFlowsToParent":"true",
            "StreamType":"Release",
            "streamName":"ArgOS_2_0_DHAL1",
            "Parent":"ArgOS_2_0",
            "Compliance":"Released",
            "children":[
               {
                  "ChangeFlowsFromParent":"false",
                  "ChangeFlowsToParent":"true",
                  "StreamType":"Release",
                  "streamName":"ArgOS_child_DHAL2",
                  "Parent":"ArgOS_2_0_DHAL1",
                  "Compliance":"Released",
                  "children":[
                     {
                        "ChangeFlowsFromParent":"false",
                        "ChangeFlowsToParent":"true",
                        "StreamType":"Release",
                        "streamName":"ArgOS_child_Gen2",
                        "Parent":"ArgOS_child_DHAL2",
                        "Compliance":"Released"
                     }
                  ]
               }
            ]
         },
         {
            "ChangeFlowsFromParent":"true",
            "ChangeFlowsToParent":"true",
            "StreamType":"Release",
            "streamName":"ArgOS_2_0_DHAL2",
            "Parent":"ArgOS_2_0",
            "Compliance":"NA"
         },
         {
            "ChangeFlowsFromParent":"false",
            "ChangeFlowsToParent":"false",
            "StreamType":"Release",
            "streamName":"ArgOS_2_0_DHAL3",
            "Parent":"ArgOS_2_0",
            "Compliance":"NA"
         }
      ]
   }
]

这是我的模特

public class TreeModel
{
    public string StreamName { get; set; }
    public string ParentName { get; set; }
    public string StreamType { get; set; }
    public bool ChangeFlowsFromParent { get; set; }
    public bool ChangeFlowsToParent { get; set; }
    public string Compliance { get; set; }
    public string Parent { get; set; }

}

所以我有一个模型形式的数据,我需要创建一个嵌套的Json结构,就像上面提到的那样. 根据parent = streamname,必须创建一个children标签,并将该模型项添加为json数组.

So I have a data in the form of my model and I need to create a nested Json structure like the one mentioned above. Based on the parent = streamname, a children tag will have to be created and that model item would be added as a json array.

此JSON用于我的树形图.这是如何实现的?

This JSON is for my tree graph. How is this achievable?

推荐答案

每当您需要序列化数据时,都要设计一个完全适合预期的im/export结构的类结构.不在乎您的应用程序的其余部分,只需专注于im/export.

Whenever you had to serialize data design a class structure that will exactly fit to the expected im-/export structure. Do not care for the rest of your application, just focus on im-/export.

给定的JSON可以用

class TreeModelJson
{
    [JsonProperty("ChangeFlowsFromParent")]
    public string ChangeFlowsFromParent { get; set; }
    [JsonProperty("ChangeFlowsToParent")]
    public string ChangeFlowsToParent { get; set; }
    [JsonProperty("StreamType")]
    public string StreamType { get; set; }
    [JsonProperty("streamName")]
    public string StreamName { get; set; }
    [JsonProperty("Parent")]
    public string Parent { get; set; }
    [JsonProperty("Compliance")]
    public string Compliance { get; set; }
    [JsonProperty("children", NullValueHandling = NullValueHandling.Ignore)]
    public ICollection<TreeModelJson> Children { get; set; }
}

现在是时候从应用程序模型向JSON模型编写映射器了

Now it is time to write a mapper from your application model to the JSON model

static ICollection<TreeModelJson> MapToTreeModelJsonCollection(ICollection<TreeModel> source)
{
    // map all items
    var allItems = source.Select(e => new TreeModelJson
    {
        ChangeFlowsFromParent = e.ChangeFlowsFromParent.ToString().ToLower(),
        ChangeFlowsToParent = e.ChangeFlowsToParent.ToString().ToLower(),
        Compliance = e.Compliance,
        Parent = e.Parent ?? "none",
        StreamName = e.StreamName,
        StreamType = e.StreamType,
    }).ToList();

    // build tree structure
    foreach (var item in allItems)
    {
        var children = allItems.Where(e => e.Parent == item.StreamName).ToList();
        if (children.Any())
        {
            item.Children = children;
        }
    }

    // return only root items
    return allItems.Where(e => e.Parent == "none").ToList();
}

现在是时候将它们整合在一起

Now it is time to bring it all together

var source = new List<TreeModel>
{
    ... // populate some data
};
var output = MapToTreeModelJsonCollection(source);
var json = JsonConvert.SerializeObject(output,Formatting.Indented);

在.net小提琴上完成示例

  • JSON中的Parent属性是多余的,因为如果对象是另一个对象的子代,则已经提供了此信息

  • the Parent property in JSON is redundant, because this information is already given if the object is a children of another object

JSON知道boolean属性,最好将它们反序列化为boolean而不是string.

JSON is aware of boolean properties and it would be better to deserialize them as boolean and not as string.

这篇关于从C#模型创建嵌套的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆