0

I want to convert my ArrayList<object> to a JSON String and back to ArrayList<object>

But I really don't know how to do that :

Something like :

Convert
ArrayList<data> arrayData = new ArrayList<data>();
 JSONObject retObject = new JSONObject();
    retObject.put("data", new JSONArray(arrayData ));

    Return convert

idk...
Pragmateek
  • 13,174
  • 9
  • 74
  • 108
Domi
  • 1,299
  • 3
  • 17
  • 27
  • Which library are you using ? It is a very straight forward job in GSON ! – AllTooSir Jun 05 '14 at 09:22
  • Check: http://stackoverflow.com/questions/17037340/converting-jsonarray-to-arraylist – radimpe Jun 05 '14 at 09:27
  • Are you sure you want a JSON string and not a JSON array? – Gimby Jun 05 '14 at 09:46
  • i want to put my Arraylist into a Cookie which only supports strings – Domi Jun 05 '14 at 09:51
  • 1
    You should mention such details when asking the question the next time, at least then you provide an understandable context for your question. But while we're on this topic: you can just as easily translate the data into a string where you are creating the cookie, it does not necessarily have to happen before transmission of the data. – Gimby Jun 05 '14 at 09:57

3 Answers3

4

You can consider using a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,

// How to store JSON string

Gson gson = new Gson();
// This can be any object. Does not have to be an arraylist.

String json = gson.toJson(myAppsArr);

// How to retrieve your Java object back from the string

Gson gson = new Gson();

DataObject obj = gson.fromJson(arrayString, ArrayList.class);
Ambrish
  • 3,627
  • 2
  • 27
  • 42
Manitude
  • 100
  • 7
0

Using Jackson:

ObjectMapper mapper = new ObjectMapper();
String listAsJson = mapper.writeValueAsString(oldList);
List<Object> newList= mapper.readValue(listAsJson ,new TypeReference<List<Object>>() {});
hexin
  • 947
  • 7
  • 17
-1
ArrayList<Product> arrayData = new ArrayList<Product>();
Gson gson = new Gson();

convert list to json object

String jsonCartList = gson.toJson(cartList);

convert json to your list

List<Product> prodList = gson.fromJson(jsonCartList, Product.class);
hari
  • 1,874
  • 1
  • 16
  • 10