我用这种方式得到 Json String,
json= [{"id":"1","label":"2","code":"3"},{"id":"4","label":"5","code":"6"}]
我尝试使用 Gson 以这种方式将它转换为 Java 对象,
还有一个名为 Item.java 的 Pojo,其中包含 id、label 和 code 字段以及它们的 getter setter。
String id;
String label;
String code;
//getter setters
Gson gson = new Gson();
List<Item> items = gson.fromJson(json, new TypeToken<List<Item>>(){}.getType());
然后通过这种方式将Java Object转换为List,
List<String> strings = new ArrayList<String>();
for (Object object : items) {
strings.add(object != null ? object.toString() : null);
}
我的输出是这样的,
[Item [id=1, label=2, code=3], Item [id=6, label=5, code=6]
但我需要它作为 List<List<String>>
并且没有 [Items] 即,
[[id=1, label=2, code=3],[id=4, label=5, code=6]]
or direct
List<List<String>>
没有 key 。
[[1, 2, 3],[4, 5, 6]]
我错过了什么?有人可以帮助我吗?
最佳答案
您已经发布的代码给您一个 List<Item>
,所以听起来您只是不确定如何构建 List<List<String>>
你在这里做什么:
for (Object object : items) {
未能利用 items
的事实是 List<Item>
, 不是 List<Object>
.
您可以创建一个增强的 for 循环来提取实际的 Item
像这样:
for (Item item : items) {
这将使您能够正确访问其中的数据以构建子列表:
String json = "[{id:1,label:2,code:3},{id:4,label:5,code:6}]";
List<Item> items = new Gson().fromJson(json, new TypeToken<List<Item>>(){}.getType());
List<List<String>> listOfLists = new ArrayList<>();
for (Item item : items) {
List<String> subList = new ArrayList<>();
subList.add(item.getId());
subList.add(item.getLabel());
subList.add(item.getCode());
listOfLists.add(subList);
}
System.out.println(listOfLists); // [[1, 2, 3], [4, 5, 6]]
但是
如果只是你不喜欢List<Item>
的输出格式, 一种更简单的修复代码的方法是覆盖 toString()
以打印您需要的方式。
如果我创建 toString()
Item
中的方法看起来像这样:
public class Item {
private String id;
private String label;
private String code;
@Override
public String toString() {
return "[" + id + ", " + label + ", " + code + "]";
}
// getters, setters...
}
...然后当我打印 List<Item>
它看起来像你想要的那样:
String json = "[{id:1,label:2,code:3},{id:4,label:5,code:6}]";
List<Item> items = new Gson().fromJson(json, new TypeToken<List<Item>>(){}.getType());
System.out.println(items); // [[1, 2, 3], [4, 5, 6]]
关于java - 在 Java 中将 JSON 转换为 List<List<String>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29376032/