[英]How to convert ArrayList<object> to String and vice versa
我想将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...
您可以考虑使用JSON库(例如Google的Gson库)将对象存储和检索为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);
使用杰克逊:
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();
将列表转换为json对象
String jsonCartList = gson.toJson(cartList);
将json转换为您的列表
List<Product> prodList = gson.fromJson(jsonCartList, Product.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.