簡體   English   中英

將 json 對象反序列化為 C# 對象

[英]Deserialization json objects into C# objects

我從文件中得到 json。 它可能有不同的結構,例如它可能看起來像這樣:

    {
    "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": []
            }
        ]
    }
}

或像這樣:

    {
    "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": []
            }
        ]
    }
}

我需要將其反序列化為 c# 對象。 我已經有了一個 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; }
}

但我真的不明白如何從我的 RootElement 中提取嵌套對象,因為嵌套對象可能有不同的結構並且可能有自己的嵌套對象。

我忘了提。 我已經將 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));
        }
    }

我似乎您的 model 對應於您可能得到的 JSON 結構。 在這種情況下,您只需要讀取文件並執行反序列化。 它應該是這樣的:

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

一旦你有了根 object,你可以檢查它是否有任何級別的孩子。

更新:要遍歷孩子,你應該添加一個這樣的遞歸方法:

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

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

使用 .net 5 您可以使用System.Text.Json內置於 .net

  using System.Text.Json;

並且您的 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; }
    }

更新

根據您的評論,您需要遍歷您的孩子或創建一種方法來搜索孩子列表

完整的工作代碼

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