简体   繁体   English

如何转换ArrayList <object> 转换为字符串,反之亦然

[英]How to convert ArrayList<object> to String and vice versa

I want to convert my ArrayList<object> to a JSON String and back to ArrayList<object> 我想将ArrayList<object>转换为JSON String并返回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...

You can consider using a JSON library like Google's Gson library to store and retrieve objects as JSON strings. 您可以考虑使用JSON库(例如Google的Gson库)将对象存储和检索为JSON字符串。 This is a lightweight library, well regarded and popular. 这是一个轻量级的库,备受推崇并广受欢迎。 It would be an ideal solution in your case with minimal work required. 对于您的情况而言,这是一种理想的解决方案,只需很少的工作即可。 eg, 例如,

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

Using Jackson: 使用杰克逊:

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

convert list to json object 将列表转换为json对象

String jsonCartList = gson.toJson(cartList);

convert json to your list 将json转换为您的列表

List<Product> prodList = gson.fromJson(jsonCartList, Product.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM