简体   繁体   English

将 json 对象反序列化为 C# 对象

[英]Deserialization json objects into C# objects

I'm getting json from file.我从文件中得到 json。 It could have a different stucture, for examle it could look like this:它可能有不同的结构,例如它可能看起来像这样:

    {
    "root": {
        "name": "LWindow",
        "children": [{
                "name": "Label",
                "children": []
            },
            {
                "name": "Edit",
                "children": []
            },
            {
                "name": "Label",
                "children": []
            },
            {
                "name": "Radio",
                "children": []
            },
            {
                "name": "Checkbox",
                "children": []
            },
            {
                "name": "Label",
                "children": []
            },
            {
                "name": "Label",
                "children": []
            }
        ]
    }
}

or like this:或像这样:

    {
    "root": {
        "name": "LWindow",
        "children": [{
                "name": "FormItem",
                "children": [{
                        "name": "Label",
                        "children": []
                    },
                    {
                        "name": "Edit",
                        "children": []
                    }
                ]
            },
            {
                "name": "FormItem",
                "children": [{
                        "name": "Label",
                        "children": []
                    },
                    {
                        "name": "Edit",
                        "children": []
                    }
                ]
            },
            {
                "name": "FormItem",
                "children": [{
                        "name": "Label",
                        "children": []
                    },
                    {
                        "name": "Radio",
                        "children": []
                    }
                ]
            },
            {
                "name": "Label",
                "children": []
            },
            {
                "name": "Button",
                "children": []
            }
        ]
    }
}

What I need is to deserialize it to c# objects.我需要将其反序列化为 c# 对象。 I've already got a class, that describes json:我已经有了一个 class,它描述了 json:

public partial class Root
{
    public RootElement RootRoot { get; set; }
}

public partial class RootElement
{
    public string Name { get; set; }
    public List<RootElement> Children { get; set; }
}

But I don't really understand how to extract nested objects from my RootElement because nested objects could have different structure and could have their own nested objects.但我真的不明白如何从我的 RootElement 中提取嵌套对象,因为嵌套对象可能有不同的结构并且可能有自己的嵌套对象。

I forgot to metion.我忘了提。 I've alredy deserialized json to my Root with:我已经将 json 反序列化到我的根目录:

public static T DeserializeJson<T>(String pathToJSON)
    {
        using (StreamReader file = File.OpenText(pathToJSON))
        {
            JsonSerializer serializer = new JsonSerializer();
            return (T)serializer.Deserialize(file, typeof(T));
        }
    }

I seems that your model is corresponding to the JSON structure you might get.我似乎您的 model 对应于您可能得到的 JSON 结构。 In such case, you only need to read the file and perform the deserialization.在这种情况下,您只需要读取文件并执行反序列化。 It should be something like this:它应该是这样的:

string json = File.ReadAllText("File path");
Root root = JsonSerializer.Deserialize<Root>(json);

Once you have the Root object, you can check if it has children at any level.一旦你有了根 object,你可以检查它是否有任何级别的孩子。

Update: To traverse the children, you should add a recursive method like this:更新:要遍历孩子,你应该添加一个这样的递归方法:

private void Traverse(RootElement element)
{
    foreach (var child in element.Children)
    {
        // Do something with the child

        this.Traverse(child); // Traverse the child recursively
    }
}

With .net 5 you can use System.Text.Json which is built in .net使用 .net 5 您可以使用System.Text.Json内置于 .net

  using System.Text.Json;

and the name of properties in your class should be the same as in JSON field or annotate it by JSON names as following并且您的 class 中的属性名称应与 JSON 字段中的相同,或者通过 JSON 名称对其进行注释,如下所示

public partial class Root
    {
        [JsonPropertyName("root")]
        public RootElement RootRoot { get; set; }
    }

public partial class RootElement
    {
        [JsonPropertyName("name")]
        public string Name { get; set; }
        [JsonPropertyName("children")]
        public List<RootElement> Children { get; set; }
    }

update更新

based on your comment you need to loop over your children or create a method to search on children list根据您的评论,您需要遍历您的孩子或创建一种方法来搜索孩子列表

full working code完整的工作代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace ConsoleApp3
{
    public  class Root
    {
        [JsonPropertyName("root")]
        public RootElement RootRoot { get; set; }
    }

    public  class RootElement
    {
        [JsonPropertyName("name")]
        public string Name { get; set; }
        [JsonPropertyName("children")]
        public List<RootElement> Children { get; set; }
    }

   
    
    class Program
    {

        static IEnumerable<RootElement> GetElements( List<RootElement> chelderins, string serchName)
        {
            foreach (var child in chelderins)
            {
                if (child.Name == serchName)yield return child;
            }
        }
        static void Main(string[] args)
        {
            string jsonContent = File.ReadAllText("file.json");
            Root op = JsonSerializer.Deserialize<Root>(jsonContent);
            // now op is contains value from your json
           var Labels= GetElements(op.RootRoot.Children,"Label").ToList() ;
            // labels now is an list with all childen contains name = lablel

            var checkBoxes = GetElements(op.RootRoot.Children, "Checkbox").ToList();


        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM