【问题标题】:Convert JSON to List<List<String>> in Java在 Java 中将 JSON 转换为 List<List<String>>
【发布时间】:2015-06-05 05:29:31
【问题描述】:

我以这种方式拥有 Json 字符串,

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&lt;List&lt;String&gt;&gt; 并且没有 [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&lt;List&lt;String&gt;&gt;,还是只是您不喜欢Item#toString() 格式化数据的方式?
  • 我真的没有在这里看到列表。我个人认为你不需要一个。 ItemtoString 方法是什么样的?

标签: java json string arraylist gson


【解决方案1】:

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

你在这里做什么:

for (Object object : items) {

没有利用itemsList&lt;Item&gt;,而不是List&lt;Object&gt;这一事实。

您可以创建一个增强的 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&lt;Item&gt; 的输出格式,更简单的修复代码的方法是覆盖 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&lt;Item&gt; 时,它看起来就像你想要的那样:

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

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 2022-01-05
    • 1970-01-01
    • 2021-08-08
    • 2022-01-11
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多