[java] Add JsonArray to JsonObject

I googled a lot today for this subject. But I can't find it, How can I add a JSONArray to a JSONObject?

Because everytime I do this I get this error: Stackoverflow

        JSONObject fillBadkamerFormaatFromContentlet(Structure structure, String formaat) {
    JSONObject jsonObject = new JSONObject();
    JSONArray arr = new JSONArray();

    BadkamerFormaat badkamerFormaat = new BadkamerFormaat();
    BadkamerTegel badkamerTegel;
    List<Contentlet> contentlets = getContentletsByStructure(structure);
    badkamerFormaat.formaat = formaat;
    badkamerFormaat.tegels = new ArrayList<BadkamerTegel>();

    try {
        jsonObject.put("formaat", formaat); 
    } catch (JSONException e1) {
        throw new RuntimeException(e1);
    }

    for(Contentlet contentlet : contentlets) {
        badkamerTegel = new BadkamerTegel();
        badkamerTegel.naam = contentlet.getStringProperty(ParameterNames.toolBetegelVeldNaam);
        try {
            badkamerTegel.afbeeldingTegel = contentlet.getBinary(ParameterNames.toolBetegelVeldTegelAfbeelding).getPath();
            badkamerTegel.afbeeldingBadkamer = contentlet.getBinary(ParameterNames.toolBetegelVeldBadkamerAfbeelding).getCanonicalPath();
            arr.put(badkamerTegel.toJSON());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }   
    }

    try {
        jsonObject.put("aoColumnDefs",arr);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

    return jsonObject;          
}

I get this error:

java.lang.StackOverflowError
at com.dotmarketing.util.json.JSONArray.<init>(JSONArray.java:248)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953)

The JSON I want: Only the last JsonArray is going wrong:

{
           "wand": [
        {
            formaat: 'vierkant15x15'
            tegels: [
                    {naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'}
                    ,{naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'}
                    ]
        }
        ,

        {
            formaat: 'vierkant17x15'
            tegels: [
                    {naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'}
                    ,{naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'}
                    ]
        }
    ]

, "vloer": [ { formaat: 'vierkant10x15' tegels: [ {naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'} ,{naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'} ] } ,

        {
            formaat: 'vierkant45x15'
            tegels: [
                    {naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'}
                    ,{naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'}
                    ]
        }
    ]

}

This question is related to java json arrays

The answer is


I'm starting to learn about this myself, being very new to android development and I found this video very helpful.

https://www.youtube.com/watch?v=qcotbMLjlA4

It specifically covers to to get JSONArray to JSONObject at 19:30 in the video.

Code from the video for JSONArray to JSONObject:

JSONArray queryArray = quoteJSONObject.names();

ArrayList<String> list = new ArrayList<String>();

for(int i = 0; i < queryArray.length(); i++){
    list.add(queryArray.getString(i));
}

for(String item : list){
    Log.v("JSON ARRAY ITEMS ", item);
}

Your list:

List<MyCustomObject> myCustomObjectList;

Your JSONArray:

// Don't need to loop through it. JSONArray constructor do it for you.
new JSONArray(myCustomObjectList)

Your response:

return new JSONObject().put("yourCustomKey", new JSONArray(myCustomObjectList));

Your post/put http body request would be like this:

    {
        "yourCustomKey: [
           {
               "myCustomObjectProperty": 1
           },
           {
               "myCustomObjectProperty": 2
           }
        ]
    }

Just try below a simple solution:

JsonObject body=new JsonObject();
body.add("orders", (JsonElement) orders);

whenever my JSON request is like:

{
      "role": "RT",
      "orders": [
        {
          "order_id": "ORDER201908aPq9Gs",
          "cart_id": 164444,
          "affiliate_id": 0,
          "orm_order_status": 9,
          "status_comments": "IC DUE - Auto moved to Instruction Call Due after 48hrs",
          "status_date": "2020-04-15",
        }
      ]
    }

here is simple code

List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
        array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
    obj.put("result", array);
} catch (JSONException e) {
 // TODO Auto-generated catch block
e.printStackTrace();
}
pw.write(obj.toString());

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?