Home > Enterprise >  How to create a list from nested JSON
How to create a list from nested JSON

Time:06-02

I have a JSON which looks like this :

{
    "operations": [
        {
            "creationTime": "2022-05-31T18:15:47.927 03:00",
            "status": "PENDING",
            "com_model_golfController": {
                "Mode": 0,
                "StopStationPayload": "[{\"ControllerAddress\":11,\"StationAddress\":26}]"
            },
            "description": "Stop Station"
        },
        {
            "creationTime": "2022-05-31T18:15:47.927 03:00",
            "status": "PENDING",
            "com_model_golfController": {
                "Mode": 0,
                "StopStationPayload": "[{\"ControllerAddress\":12,\"StationAddress\":27}]"
            },
            "description": "Stop Station"
        }
    ],
    "statistics": {
        "currentPage": 1,
        "pageSize": 5
    }
}

I have created following classes : -

public class RootObject
{
    public List<operation> operations { get; set; }
}

public class operation
{
    public golfController com_model_golfController { get; set; }
}

public class golfController
{
    public int mode { get; set; }
    public string StopStationPayload { get; set; }
} 

I've been trying different things but not able to get the desired result. Is my approach to form the above classes correct? I'm new to c# and trying to implement it.

What I want to achieve is to create a list which will contain objects : -

{
   "Mode": 0,
   "StopStationPayload": "[{\"ControllerAddress\":11,\"StationAddress\":26}]"
},
{
   "Mode": 0,
   "StopStationPayload": "[{\"ControllerAddress\":12,\"StationAddress\":27}]"
}

Any suggestion would be very helpful.

CodePudding user response:

Basically this question is not about JSON. It's about linq.

After deserializing your JSON with whatever library you use, you can obtain your golfController objects using linq and then serialize them.

var root = JsonConvert.DeserializeObject<RootObject>(json);
var controllers = root.operations.Select(o=>o.com_model_golfController).ToList()
var result = JsonConvert.SerializeObject(controllers);
  • Related