简体   繁体   中英

Deserialization json objects into C# objects

I'm getting json from file. 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. I've already got a class, that describes 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.

I forgot to metion. I've alredy deserialized json to my Root with:

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. 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.

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

  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

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();


        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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