Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DataTable to JSON with only Value

Tags:

json

c#

If I have a datatable in the following structure.

HostelName      FloorName   FlatName    Occupied    Vacant
Building One    Floor A         A           2          2
Building One    Floor A         B           0          4
Building One    Floor A         C           0          4
Building One    Floor A         D           0          4
Building One    Floor A         E           0          4
Building One    Floor B         F           0          4
Building One    Floor B         G           0          4
Building One    Floor B         H           0          4
Building One    Floor B         I           0          4
Building One    Floor B         J           0          4

I would like to serialize it as a JSON object where the HostelName,FloorName & FlatName columns are the nodes in the JSON object like:

{
    "Building One": {
        "Floor A": {
            "A": {
                "Occupied": "2",
                "Vacant": "2"
            },
            "B": {
                "Occupied": "0",
                "Vacant": "4"
            },
            "C": {
                "Occupied": "0",
                "Vacant": "4"
            },
            "D": {
                "Occupied": "0",
                "Vacant": "4"
            },
            "E": {
                "Occupied": "0",
                "Vacant": "4"
            }
        },
        "Floor B": {
            "F": {
                "Occupied": "0",
                "Vacant": "4"
            },
            "G": {
                "Occupied": "0",
                "Vacant": "4"
            },
            "H": {
                "Occupied": "0",
                "Vacant": "4"
            },
            "D": {
                "Occupied": "0",
                "Vacant": "4"
            },
            "I": {
                "Occupied": "0",
                "Vacant": "4"
            }
        }
    }
};

Please help me to solve it.

like image 605
Subin Avatar asked Nov 10 '22 08:11

Subin


1 Answers

All you have to do is using a custom JSONConverter (in case of useing JSON.NET), learn about that here (JSON.NET Implementing Custom Serialization).

like image 125
Hamed Zakery Miab Avatar answered Nov 14 '22 23:11

Hamed Zakery Miab