Skip to content
Advertisement

How to assign to a new array an array of objects?

I can’t figure out how I would do the ff.

I have the ff. Payload

   {
    "code": null,
    "message": null,
    "recCtrlOut": {
    },
    "acctSumm": [
        {
            "acctBasic": {
                "acctType": "SV",
                "acctId": "123",
                },
            "acctBasic": {
                "acctType": "SV",
                "acctId": "321",
                }
}
]
        
}

And I just want to get the acctId params and assign it to a new plain array of accountIds. How do I do it in Spring/Java?. Thanks

Advertisement

Answer

Try using json path. Library can be found here. E.g. say you had json like this:

{
  "code": null,
  "message": null,
  "recCtrlOut": {
  },
  "acctSumm": [
    {
      "acctBasic": {
        "acctType": "SV",
        "acctId": "123"
      }
    },
    {
      "acctBasic": {
        "acctType": "SV",
        "acctId": "321"
      }
    }
  ]
}

Actual code would be something like:

List<String> ids = JsonPath.read(json, "$.acctSumm[*].acctBasic.acctId");

The above list will now hold:

["123","321"]

If you wanna learn json path syntax, you could try using this online tool. Here is also a guide to help you get started with json path.

Advertisement