将 JSON 转换为 Java 中的列表 <List<String>>

Convert JSON to List<List<String>> in Java

我有 Json 这样的字符串,

json= [{"id":"1","label":"2","code":"3"},{"id":"4","label":"5","code":"6"}]

我尝试使用 Gson 以这种方式将其转换为 Java 对象,

和一个名为 Item.java 的 Pojo,其中包含 id、label 和 code 字段以及它们的 getter 设置器。

String id;
    String label;
    String code;
    //getter setters

Gson gson = new Gson();
List<Item> items = gson.fromJson(json, new TypeToken<List<Item>>(){}.getType());

然后将Java对象转换为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>>

没有钥匙。

[[1, 2, 3],[4, 5, 6]]

我缺少什么?有人可以帮助我吗?

您已经发布的代码为您提供了一个 List<Item>,所以听起来您只是不确定如何从中构建一个 List<List<String>>

你在这里做什么:

for (Object object : items) {

没有利用 itemsList<Item> 而不是 List<Object> 的事实。

您可以创建一个增强的 for 循环,像这样提取实际的 Items:

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(),使其打印出什么你需要。

如果我在 Item 中创建 toString() 方法如下所示:

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]]