134

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"}]
starball
  • 20,030
  • 7
  • 43
  • 238
pmko
  • 5,071
  • 3
  • 23
  • 25

9 Answers9

137

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:

Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
Nanne
  • 64,065
  • 16
  • 119
  • 163
  • 3
    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. – pmko Jan 30 '11 at 09:29
  • 1
    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. – Nanne Jan 30 '11 at 09:31
  • 3
    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. – pmko Jan 30 '11 at 09:40
77

Use Gson library to convert ArrayList to JsonArray.

Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();
Purushotham
  • 3,770
  • 29
  • 41
46

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);
zionpi
  • 2,593
  • 27
  • 38
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();
            }
        }

    }
dhamat chetan
  • 61
  • 1
  • 3
  • 2
    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... – C-- Oct 20 '15 at 10:04
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)
Suraj Vaishnav
  • 7,777
  • 4
  • 43
  • 46
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);
Deep Patel
  • 2,584
  • 2
  • 15
  • 28
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

ralphgabb
  • 10,298
  • 3
  • 47
  • 56
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);
Deniz Husaj
  • 89
  • 1
  • 2
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;
    }
zingh
  • 404
  • 4
  • 11