you need to make a JSON Array first and then store that

private String mUrl;
private ArrayList<String> mUrlDove;

HashMap<String, String> params = new HashMap<String, String>();
        params.put("url", mUrl);
        JSONArray jsArray = new JSONArray(mUrlDove);
        params.put("urlDove", jsArray.toString()); 

        mUrl = app.getInstance().getmUrlRestWS() + getString(R.string.path);

        JsonObjectRequest mRequest = new JsonObjectRequest(
                mUrl, new JSONObject(params),
                createMyReqSuccessListener(),
                createMyReqErrorListener()) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return app.getInstance().createBasicAuthHeader();
            }
        };
Answer from Tomer Shemesh on Stack Overflow
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-can-we-add-a-jsonarray-to-jsonobject-in-java
How can we add a JSONArray to JSONObject in Java?
July 4, 2020 - We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method. import org.json.*; import java.util.*; public class AddJSONArrayToJSONObjTest ...
Discussions

java - Creating an ArrayList from a JSON Object - Stack Overflow
So I have a JSON just like the picture below stored as MYJSON-- My plan is to retrieve all the object from childObject0 and store them in an ArrayList so they can be processed later. So I did- Arr... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - How to add ArrayList<String> to JSON Array - keeping type safety in mind - Stack Overflow
Eclipse displayed a type safety warning and I tried nearly everything to eradicate it (of course suppressing it would be an option) but unfortunately I hadn't any success. Do you know how I have to More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - How to convert ArrayList to JSON object - Stack Overflow
ArrayList mylist = new ArrayList (); mylist.add("abc"); mylist.add("cfd"); mylist.add("ert"); mylist.add("fg"); mylist.add("ujk"); String json = new Gson().toJson(mylist); You can refer to the GSON User Guide for more support. ... Sign up to request clarification or add additional context in comments. ... i am trying to convert the array into json object... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Json object to java arraylist - Stack Overflow
1 (Gson) JSON to Java objects containing ArrayList More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/androiddev โ€บ how do i save an arraylist with json?
r/androiddev on Reddit: How do I save an ArrayList<(Custom object here)> with JSON?
July 21, 2014 -
public class Semester {    
private static final String JSON_ID = "id";
private static final String JSON_TITLE = "title";
private static final String JSON_CREDITS = "credits";
private static final String JSON_GPA = "gpa";
private static final String JSON_CUMULATIVECREDITS = "cumulativecredits";
private static final String JSON_CUMULATIVEGPA = "cumulativegpa";
private static final String JSON_COURSES = "courses";

private UUID id;
private String title;
private int credits;
private double GPA;
private int cumulativeCredits;
private double cumulativeGPA;

private ArrayList<Course> courses;

public Semester() {
    id = UUID.randomUUID();
    courses = new ArrayList<Course>();
    for (int i = 0; i < 6; i++) {
        courses.add(new Course());
    }
}

public Semester(JSONObject json) throws JSONException {
    id = UUID.fromString(json.getString(JSON_ID));
    title = json.getString(JSON_TITLE);
    credits = json.getInt(JSON_CREDITS);
    GPA = json.getDouble(JSON_GPA);
    cumulativeCredits = json.getInt(JSON_CUMULATIVECREDITS);
    cumulativeGPA = json.getDouble(JSON_CUMULATIVEGPA);

//what do i put here?

}

public JSONObject toJSON() throws JSONException {
    JSONObject json = new JSONObject();
    json.put(JSON_ID, id.toString());
    json.put(JSON_TITLE, title);
    json.put(JSON_CREDITS, credits);
    json.put(JSON_GPA, GPA);
    json.put(JSON_CUMULATIVECREDITS, cumulativeCredits);
    json.put(JSON_CUMULATIVEGPA, cumulativeGPA);

JSONArray array = new JSONArray(courses);

json.put(JSON_COURSES, array);

    return json;
}

.........

This is followed by a bunch of getters and setters for each private variable.

  • The first bolded item is the private ArrayList of a custom class that I made.

  • The second bolded item is what I need help with: how to retrieve the custom ArrayList just like the other variables.

  • Lastly, the third bolded item is my current idea of how to put an ArrayList into a JSONObject, but I don't know how to retrieve it. If there is another way, please tell me. Thank you.

Find elsewhere
๐ŸŒ
YouTube
youtube.com โ€บ watch
Java JSON Array Encode Using ArrayList - YouTube
#JavaJSONArray #HomeStay #StaySafe #ArrayList #JSONArrayListJava JSON ArrayList Encode0:05 JSON Install1:53 JSON Array Example Start time:Like, Share, And Su...
Published: April 7, 2020
Top answer
1 of 2
26

You can use the putArray method which creates an ArrayNode. Then you should fill it with the elements from your list.

ArrayNode arrayNode = row.putArray("myList");
for (String item : list) {
    arrayNode.add(item);
}
2 of 2
0

Here is a functional way of creating an arrayNode and populate it elements from a stream. It does the same as above fracz answer :

    yourStringList.stream()
        .collect(Collector.of(
            () -> row.putArray("myList"), 
            (arrayNode, item) -> arrayNode.add(item), 
            (arrayNode1, arrayNode2) -> { arrayNode1.addAll(arrayNode2);  return arrayNode1; },
            Collector.Characteristics.IDENTITY_FINISH
        ));

Essentially, it defines a custom collector to accumulate the elements provided by the stream. Some explanations:

  • the first argument () -> row.putArray("myList") defines the function which will provide the object to accumulate the items (called the supplier function). In our case this function will provide the ArrayNode and is the equivalent of ArrayNode arrayNode = row.putArray("myList"); statement in the above answer.
  • the second argument (arrayNode, item) -> arrayNode.add(item) defines the accumulator function whose role is to add the elements. In the left side of the -> operator, the first variable (e.g. arrayNode) refers to the container defined in the first argument while the second (e.g. item) refers to the element to accumulate provided by the stream. This function does the same job as the statement arrayNode.add(item); inside the loop in the above example.
  • the third argument (arrayNode1, arrayNode2) -> { arrayNode1.addAll(arrayNode2); return arrayNode1; } is the combiner function which is used if the stream is collected in parralel (for instance if we had .parralelStream() instead of .stream()). Its role is to merge two accumulators toghether and this is why the function has two argumets of the same type. We define this function such that it will add all elements accumulated in the second accumulator into the first accumulator and return this first accumulator.
  • the fourth argument Collector.Characteristics.IDENTITY_FINISH define one or more optons to the process. In this case, IDENTITY_FINISH simply states that no finisher function will be provided (to further process the accumulator object) or, in other words, that the finisher function is the identity function (no treatment done).

This solution might seems more complex at first but it leverages all the power of functionnal programming. For instance, we could stream objects, extract a String property with the map function, filter it, etc. before collecting everything:

    yourObjectList.stream()
        .map(o -> o.getTheStringProperty())
        .filter(o -> o.length() > MIN_SIZE)
        .collect(Collector.of(
            () -> row.putArray("myList"), 
            (arrayNode, item) -> arrayNode.add(item), 
            (arrayNode1, arrayNode2) -> { arrayNode1.addAll(arrayNode2);  return arrayNode1; },
            Collector.Characteristics.IDENTITY_FINISH
        ));
๐ŸŒ
Tabnine
tabnine.com โ€บ home โ€บ code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 60019377 โ€บ how-to-make-a-arraylist-with-json-objects-in-java
How to make a Arraylist with JSON Objects in JAVA? - Stack Overflow
It's generally worth doing a search for common programming tasks. You could just google search "java add to list" which should result in something like: List<JSONObject> myList = new ArrayList<>(); myList.add(uptimeResponsObject);
Top answer
1 of 5
20

Call getJSONObject() instead of getString(). That will give you a handle on the JSON object in the array and then you can get the property off of the object from there.

For example, to get the property "value" from a List<SomeClass> where SomeClass has a String getValue() and setValue(String value):

JSONObject obj = new JSONObject();
List<SomeClass> sList = new ArrayList<SomeClass>();

SomeClass obj1 = new SomeClass();
obj1.setValue("val1");
sList.add(obj1);

SomeClass obj2 = new SomeClass();
obj2.setValue("val2");
sList.add(obj2);

obj.put("list", sList);

JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
  System.out.println(jArray.getJSONObject(ii).getString("value"));
2 of 5
3

Let us assume that the class is Data with two objects name and dob which are both strings.

Initially, check if the list is empty. Then, add the objects from the list to a JSONArray

JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<String>();

    //if List not empty
    if (!(sList.size() ==0)) {

        //Loop index size()
        for(int index = 0; index < sList.size(); index++) {
            JSONObject eachData = new JSONObject();
            try {
                eachData.put("name", sList.get(index).getName());
                eachData.put("dob", sList.get(index).getDob());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            allDataArray.put(eachData);
        }
    } else {
        //Do something when sList is empty
    }
    

Finally, add the JSONArray to a JSONObject.

JSONObject root = new JSONObject();
    try {
        root.put("data", allDataArray);
    } catch (JSONException e) {
        e.printStackTrace();
    }

You can further get this data as a String too.

String jsonString = root.toString();
๐ŸŒ
YouTube
youtube.com โ€บ watch
Java json 01 create an arraylist to serialize with Jackson library - YouTube
Shows how to prepare an arraylist of a class. Preparing for use of a json library called Jackson. Part 1 of 3 for how to read and write json files using java
Published: January 29, 2019
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ how-to-convert-java-array-or-arraylist-to-jsonarray-using-gson-in-java
How to convert Java array or ArrayList to JsonArray using Gson in Java?
July 8, 2020 - import com.google.gson.*; import java.util.*; public class JavaArrayToJsonArrayTest { public static void main(String args[]) { String[][] strArray = {{"elem1-1", "elem1-2"}, {"elem2-1", "elem2-2"}}; ArrayList<ArrayList<String>> arrayList = new ArrayList<>(); for(int i = 0; i < strArray.length; i++) { ArrayList<String> nextElement = new ArrayList<>(); for(int j = 0; j < strArray[i].length; j++) { nextElement.add(strArray[i][j] + "-B"); } arrayList.add(nextElement); } JsonObject jsonObj = new JsonObject(); // array to JsonArray JsonArray jsonArray1 = new Gson().toJsonTree(strArray).getAsJsonArray(); // ArrayList to JsonArray JsonArray jsonArray2 = new Gson().toJsonTree(arrayList).getAsJsonArray(); jsonObj.add("jsonArray1", jsonArray1); jsonObj.add("jsonArray2", jsonArray2); System.out.println(jsonObj.toString()); } }
๐ŸŒ
Javatpoint
javatpoint.com โ€บ how-to-convert-json-array-to-arraylist-in-java
How to Convert JSON Array to ArrayList in Java - Javatpoint
How to Convert JSON Array to ArrayList in Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.