【问题标题】:How to convert ArrayList<object> to String and vice versa如何将 ArrayList<object> 转换为 String,反之亦然
【发布时间】:2014-06-05 09:20:15
【问题描述】:

我想将我的 ArrayList&lt;object&gt; 转换为 JSON String 并返回到 ArrayList&lt;object&gt;

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

类似:

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

    Return convert

idk...

【问题讨论】:

  • 您使用的是哪个库?在 GSON 中这是一项非常简单的工作!
  • 您确定要 JSON 字符串而不是 JSON 数组吗?
  • 我想把我的 Arraylist 放到一个只支持字符串的 Cookie 中
  • 你应该在下次提问时提及这些细节,至少你可以为你的问题提供一个可以理解的上下文。但是,当我们讨论这个主题时:您可以轻松地将数据转换为要在其中创建 cookie 的字符串,但不一定必须在数据传输之前发生。

标签: java json arraylist


【解决方案1】:

您可以考虑使用像 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);

【讨论】:

    【解决方案2】:

    使用杰克逊:

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

    【讨论】:

    • 不完全是 JSON,我不认为。
    • 别担心,伙计,在你被否决之前删除回复
    • 我把它改成了杰克逊,可以吗?
    • 我不会投反对票,但就个人而言,我更喜欢xstream
    • 我使用 xstream 进行 xml 解析和操作,如果是 json 它取决于项目
    【解决方案3】:
    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);
    

    【讨论】:

    • 最后一行不会导致类型不匹配吗?
    猜你喜欢
    • 2012-05-14
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 2018-05-18
    相关资源
    最近更新 更多