简体   繁体   中英

How do I deserialize a tree of objects into a DTO?

I am attempting to deserialize a tree of JSon objects I get back into a DTO. The tree can be up to 4 levels deep, and over 1200 nodes. The code is C# using Newtonsoft.Json for deserialization.

EDIT

The JSon looks like:

[
{
    "id": 1095,
    "name": "Item1-1",
    "children": [
        {
            "id": 1097,
            "name": "Item2-2",
            "children": [
                {
                    "id": 18,
                    "name": "Item3-3",
                    "children": [
                        {
                            "id": 19,
                            "name": "Item4-4",
                            "children": [],
                            "level": 4,
                            "parentId": 18
                        },
                        {
                            "id": 20,
                            "name": "Item5-4",
                            "children": [],
                            "level": 4,
                            "parentId": 18
                        }
                    ],
                    "level": 3,
                    "parentId": 1097
                }
                ],
                "level": 2,
                "parentId": 1095
        }
    ],
    "level": 1,
    "parentId": null
}
]

My DTO is similar to this:

public class MyDTO
{
    [JsonProperty("id")]
    public int Id { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("children")]
    public MyDTO[] Children { get; set; }
    [JsonProperty("level")]
    public int Level { get; set; }
    [JsonProperty("parentId")]
    public int ParentId { get; set; }

    public MyDTO()
    {
    }
}

I like Brian Rogers' solution in this link, which deserializes the json into objects: How do I use JSON.NET to deserialize into nested/recursive Dictionary and List?

 public static class JsonHelper
{
    public static object Deserialize(string json)
    {
        return ToObject(JToken.Parse(json));
    }

    private static object ToObject(JToken token)
    {
        switch (token.Type)
        {
            case JTokenType.Object:
                return token.Children<JProperty>()
                            .ToDictionary(prop => prop.Name,
                                          prop => ToObject(prop.Value));

            case JTokenType.Array:
                return token.Select(ToObject).ToList();

            default:
                return ((JValue)token).Value;
        }
    }
}

I call the JSonHelper with object obj = JsonHelper.Deserialize(jsonString);

I have been experimenting with converting this code into a method to convert to MyDTO, but I keep running into compiler errors. I have attempted to simply convert the JValue casts with MyDTO and move on to the List with a List.

My goal is to call MyDTO obj = JsonHelp.Deserialize(jsonString) and get the tree of MyDTO objects back. Is it possible to do what I am trying, or should I find a way to cast each object to MyDTO?

First your JSON is missing a brakcet ] , then your model needs a nullable parentId . Making a couple simple changes you can then you JsonConvert.DeserializeObject<IEnumerable<MyDTO>>(json) .

So your JSON should look like this:

[
{
    "id": 1095,
    "name": "Item1-1",
    "children": [
        {
            "id": 1097,
            "name": "Item2-2",
            "children": [
                {
                    "id": 18,
                    "name": "Item3-3",
                    "children": [
                        {
                            "id": 19,
                            "name": "Item4-4",
                            "children": [],
                            "level": 4,
                            "parentId": 18
                        },
                        {
                            "id": 20,
                            "name": "Item5-4",
                            "children": [],
                            "level": 4,
                            "parentId": 18
                        }
                    ],
                    "level": 2,
                    "parentId": 1095
                }],
            }],
    "level": 1,
    "parentId": null
}
]

And can be deserialized with this model:

public class MyDTO
{
    public int Id { get; set; }
    public string Name { get; set; }
    public MyDTO[] Children { get; set; }
    public int Level { get; set; }
    public int? ParentId { get; set; }
}

Using this code:

var dto = JsonConvert.DeserializeObject<IEnumerable<MyDTO>>(json);

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