Json formatting with Json.net in C#

100 views Asked by At

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?

2

There are 2 answers

2
Joel Harkes On BEST ANSWER

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; }
}
0
Tyler Durden On

Copy your json then go in Visual Studio.
Click on "Edit" > "Paste Special" > "Paste JSON as Classes"

All the classes are automatically created. I hope this tip could help you.