Search code examples
c#jsonjson.netjsonserializerjson-serialization

Json formatting with Json.net in C#


I am trying to parse a bunch of XML files into a single JSON file, which is already working.

The final JSON file looks like the following:

{
"items": [
    {
        "subItems": [
            {
                "Name": "Name",
                "Value": "Value",
                "Type": "text"
            },
            {
                "Name": "Name",
                "Value": "Value",
                "Type": "text"
            }
        ]
    },
    {
        "subItems": [
            {
                "Name": "Name",
                "Value": "Value",
                "Type": "text"
            },
            {
                "Name": "Name",
                "Value": "Value",
                "Type": "text"
            },
...

Instead, I want to achieve the following structure:

{
"items": [
    [   
        {
            "Name": "Name",
            "Value": "Value",
            "Type": "text"
        },
        {
            "Name": "Name",
            "Value": "Value",
            "Type": "text"
        }

    ],
    [
        {
            "Name": "Name",
            "Value": "Value",
            "Type": "text"
        },
        {
            "Name": "Name",
            "Value": "Value",
            "Type": "text"
        }
    ]
]
}

But I don't know how to define my objects in order to do so, my current structure is as follows:

public class Items
{
    public List<Item> items;
}

public class Item
{
    public List<SubItem> subItems;
}

public class SubItem
{
    public string Name { get; set; }
    public string Value { get; set; }
    public string Type { get; set; }
}

How should I do this?


Solution

  • The answer is simple: turn your objects into lists: This will remove the prop names (and object notation in json).

    public class Items
    {
        public List<Item> items; //list with prop name 'items'
    }
    
    public class Item : List<SubItem> // list in list like json notation
    {
    }
    
    public class SubItem // Object in the list in list
    {
        public string Name { get; set; }
        public string Value { get; set; }
        public string Type { get; set; }
    }
    

    As @FlilipCordas noted Inheriting from list is bad practice (for good reason) you are better of this way:

    public class Items
    {
        public List<List<SubItem>> items; //list with list with prop name 'items'
    }
    
    public class SubItem // Object in the list in list
    {
        public string Name { get; set; }
        public string Value { get; set; }
        public string Type { get; set; }
    }