如何将ArrayList <object>转换为String,反之亦然</object>

时间:2014-06-05 09:20:15

标签: java json arraylist

我想将ArrayList<object>转换为 JSON String并返回ArrayList<object>

但我真的不知道该怎么做:

类似的东西:

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

    Return convert

idk...

3 个答案:

答案 0 :(得分:3)

您可以考虑使用Google的Gson库等JSON库来存储和检索JSON字符串对象。这是一个轻量级的图书馆,备受推崇和受欢迎。在您的情况下,它将是一个理想的解决方案,只需要最少的工作如,

// 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);

答案 1 :(得分:1)

使用杰克逊:

ObjectMapper mapper = new ObjectMapper();
String listAsJson = mapper.writeValueAsString(oldList);
List<Object> newList= mapper.readValue(listAsJson ,new TypeReference<List<Object>>() {});

答案 2 :(得分:-1)

ArrayList<Product> arrayData = new ArrayList<Product>();
Gson gson = new Gson();

将列表转换为json对象

String jsonCartList = gson.toJson(cartList);

将json转换为您的列表

List<Product> prodList = gson.fromJson(jsonCartList, Product.class);
相关问题