-2

I have a JSONObject I want to convert this into an array.

{
    "confirmationTypes": [
        {
            "confirmationTypeCode": "A"
        },
        {
            "confirmationTypeCode": "B"
        }
    ]
}

array = [confirmationTypes]

Example:

[
    {
     "confirmationTypes": [
        {
            "confirmationTypeCode": "A"
        },
        {
            "confirmationTypeCode": "B"
        }
      ]
    }
]

How do I achieve this type of JSONArray format

startNet
  • 274
  • 1
  • 10
  • I don't understand what you have and what you want. The 2 piece of code are the same, except that the 2nd is an array of previous object (containing an array). – Bruno Sep 23 '19 at 13:27
  • 2
    use this to achieve what you want `JSONArray jsonArray = new JSONArray(); jsonArray.put(yourJsonObject)` – Anurag Shrivastava Sep 23 '19 at 13:31
  • Possible duplicate of [How to convert JSONObjects to JSONArray?](https://stackoverflow.com/questions/22687771/how-to-convert-jsonobjects-to-jsonarray) – Ricardo A. Sep 23 '19 at 17:44

2 Answers2

0

use com.fasterxml.jackson.databind.JsonNode library and parse your json string like below and given objectNode you can treat like a jsonArray and iterate through it.

Since "confirmationTypes" field is having an array.So fetch the value of this array using this("confirmationTypes") key.

ObjectMapper mapper = new ObjectMapper();
JsonNode objectNode = mapper.readTree(inputJson);
for(JsonNode node : objectNode.get("confirmationTypes")){
         System.out.println(node.get("confirmationTypeCode").asText());
     }

There are many features are there for json node you can even extract complex Json.

0

you can use ArrayList to achieve this output.

ArrayList<JsonObject> list = new ArrayList<JsonObject>();
list.add(yourJsonObject)

or as @Anurag Shrivastava said,

JsonArray array = new JsonArray();
array.put(yourJsonObject);

Pretty Simple

Rohit Chauhan
  • 1,119
  • 1
  • 12
  • 30