135

I have an ArrayList that I use within an ArrayAdapter for a ListView. I need to take the items in the list and convert them to a JSONArray to send to an API. I've searched around, but haven't found anything that explains how this might work, any help would be appreciated.

UPDATE - SOLUTION

Here is what I ended up doing to solve the issue.

Object in ArrayList:

public class ListItem {
    private long _masterId;
    private String _name;
    private long _category;

    public ListItem(long masterId, String name, long category) {
        _masterId = masterId;
        _name = name;
        _category = category;
    }

    public JSONObject getJSONObject() {
        JSONObject obj = new JSONObject();
        try {
            obj.put("Id", _masterId);
            obj.put("Name", _name);
            obj.put("Category", _category);
        } catch (JSONException e) {
            trace("DefaultListItem.toString JSONException: "+e.getMessage());
        }
        return obj;
    }
}

Here is how I converted it:

ArrayList<ListItem> myCustomList = .... // list filled with objects
JSONArray jsonArray = new JSONArray();
for (int i=0; i < myCustomList.size(); i++) {
        jsonArray.put(myCustomList.get(i).getJSONObject());
}

And the output:

[{"Name":"Name 1","Id":0,"Category":"category 1"},{"Name":"Name 2","Id":1,"Category":"category 2"},{"Name":"Name 3","Id":2,"Category":"category 3"}]
0

9 Answers 9

138

If I read the JSONArray constructors correctly, you can build them from any Collection (arrayList is a subclass of Collection) like so:

ArrayList<String> list = new ArrayList<String>();
list.add("foo");
list.add("baar");
JSONArray jsArray = new JSONArray(list);

References:

Sign up to request clarification or add additional context in comments.

3 Comments

That works in your example, but in mine the ArrayList is comprised of Objects and not Strings - guess i should have put that in my question. I think this is the right direction, but i may need to override toString in my class to get this to work correctly.
You could always loop over your list and use jsArray.put() for this. In the end your objects should have a toString method for them to be converted to JSONArray anyway I think, because they'll be saved as one.
That got me close, but what happened was that the toString() output from each object was inserted into the JSONArray as a String. I still ended up with an JSONArray of Strings and not Objects. I ended up creating a method on my class called getJSONObject, then looped over the ArrayList and put the result of this into the JSONArray. Thanks for putting me on the right path. I'm going to accept your answer and then post a code sample of what i ended up doing. i hope this isn't bad SO etiquette.
77

Use Gson library to convert ArrayList to JsonArray.

Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();

7 Comments

This is not a org.json.JSONArray as OP wanted, its a com.google.gson.JsonArray.
one more Id filed is aromatically added while using Gson.toJsonTree. how to prevent it.
@HiteshKamani It will not add an extra id automatically, might be your class is having an id field.
It actually depends on task. Generally not worth including entire external library to do things android SDK can suit itself. Especialy if you are at the edge of 64K methods in project.
hi uttam awesome solution just a quick thing it doesn't convert arraylist within arraylist to json array
|
47

As somebody figures out that the OP wants to convert custom List to org.json.JSONArray not the com.google.gson.JsonArray,the CORRECT answer should be like this:

Gson gson = new Gson();

String listString = gson.toJson(
                    targetList,
           new TypeToken<ArrayList<targetListItem>>() {}.getType());

 JSONArray jsonArray =  new JSONArray(listString);

5 Comments

Awesome :) You are perfect
@zionpi Here 2 libraries are being used to convert a array list to Json array
@Uttam Where can you see two libs used in this?
If am I correct, JSONArray is from org.json and Gson is from com.google.json
Gah this throws checked exception: JSONException. Otherwise the perfect answer right here.
5
public void itemListToJsonConvert(ArrayList<HashMap<String, String>> list) {

        JSONObject jResult = new JSONObject();// main object
        JSONArray jArray = new JSONArray();// /ItemDetail jsonArray

        for (int i = 0; i < list.size(); i++) {
            JSONObject jGroup = new JSONObject();// /sub Object

            try {
                jGroup.put("ItemMasterID", list.get(i).get("ItemMasterID"));
                jGroup.put("ID", list.get(i).get("id"));
                jGroup.put("Name", list.get(i).get("name"));
                jGroup.put("Category", list.get(i).get("category"));

                jArray.put(jGroup);

                // /itemDetail Name is JsonArray Name
                jResult.put("itemDetail", jArray);
                return jResult;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

1 Comment

This is one of the reason why I become a lazy programmer. I get capsule sized code for doing things from SOF. Copy paste, and everything works. Wonder when I will be replaced by a robot that does exactly the same...
3

With kotlin and Gson we can do it more easily:

  1. First, add Gson dependency:

implementation "com.squareup.retrofit2:converter-gson:2.3.0"

  1. Create a separate kotlin file, add the following methods
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

fun <T> Gson.convertToJsonString(t: T): String {
    return toJson(t).toString()
}

fun <T> Gson.convertToModel(jsonString: String, cls: Class<T>): T? {
    return try {
        fromJson(jsonString, cls)
    } catch (e: Exception) {
        null
    }
}

inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type)

Note: Do not add declare class, just add these methods, everything will work fine.

  1. Now to call:

create a reference of gson:

val gson=Gson()

To convert array to json string, call:

val jsonString=gson.convertToJsonString(arrayList)

To get array from json string, call:

val arrayList=gson.fromJson<ArrayList<YourModelClassName>>(jsonString)

To convert a model to json string, call:

val jsonString=gson.convertToJsonString(model)

To convert json string to model, call:

val model=gson.convertToModel(jsonString, YourModelClassName::class.java)

Comments

2

Add to your gradle:

implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

Convert ArrayList to JsonArray

JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);

Comments

1

I know its already answered, but theres a better solution here use this code :

for ( Field f : context.getFields() ) {
     if ( f.getType() == String.class ) || ( f.getType() == String.class ) ) {
           //DO String To JSON
     }
     /// And so on...
}

This way you can access variables from class without manually typing them..

Faster and better .. Hope this helps.

Cheers. :D

Comments

1

Here is a solution with jackson:

You could use the ObjectMapper to receive a JSON String and then convert the string to a JSONArray.

import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONArray;

List<CustomObject> myList = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(myList);
JSONArray jsonArray = new JSONArray(jsonString);

Comments

0

Improving on OP's answer when there are a lot of fields. could cut down some code with field enumeration ... ( but know that reflection is slower.)

public JSONObject getJSONObject() {
        JSONObject obj = new JSONObject();
        Field[] fields = ListItem.class.getDeclaredFields();
        for (Field f : fields) {
            try {
                obj.put(f.getName(), f.get(ListItem.this));
            } catch (JSONException | IllegalAccessException e) {
            }

        }
        return obj;
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.