【问题标题】:How to parse JSON to list of strings?如何将 JSON 解析为字符串列表?
【发布时间】:2014-04-04 21:41:02
【问题描述】:

我有一个 json 文件。

{
    "data" : [
        "my/path/old",
        "my/path/new"
    ]
}

我需要将它转换为字符串的 ArrayList。如何使用 Jackson 库?

更新:

我的代码:

Gson gson = new Gson();        
JsonReader reader = new JsonReader(new InputStreamReader(FileReader.class.getResourceAsStream(file)));

List<String> list = (ArrayList) gson.fromJson(reader, ArrayList.class);

for (String s : list) {
    System.out.println(s);
}

我的例外:

Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 1

我的最新消息

UPD2:

Gson gson = new Gson();
Type list = new TypeToken<List<String>>(){}.getType();
JsonReader reader = new JsonReader(new InputStreamReader(FileReader.class.getResourceAsStream(file)));
List<String> s = gson.fromJson(reader, list);
System.out.println(s);

【问题讨论】:

  • 他们使用 GSON 和 JSR 353。
  • 看第一个答案。
  • 正确答案是使用jackson@Flavio
  • 您的 JSON 是一个对象,而不是一个数组。没有明显的方法可以将其转换为 List。你想要名为data 的数组吗?

标签: java jackson


【解决方案1】:

您已经标记了 Jackson,但在您的示例中使用了 Gson。我要和杰克逊一起去

String json = "{\"data\":[\"my/path/old\",\"my/path/new\"]}"; // or wherever you're getting it from

创建您的ObjectMapper

ObjectMapper mapper = new ObjectMapper();

将 JSON 字符串作为树读取。由于我们知道它是一个对象,因此您可以将 JsonNode 转换为 ObjectNode

ObjectNode node = (ObjectNode)mapper.readTree(json);

获取名为dataJsonNode

JsonNode arrayNode = node.get("data");

将其解析为ArrayList&lt;String&gt;

ArrayList<String> data = mapper.readValue(arrayNode.traverse(), new TypeReference<ArrayList<String>>(){});

打印出来

System.out.println(data);

给予

[my/path/old, my/path/new]

【讨论】:

  • @Flavio 你确定你的 JSON 格式正确吗?您可能希望将其转换为 String 并打印出来,然后再将其传递给您的 ObjectMapper。我也在使用 Jackson 2。您可能希望升级。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-13
  • 1970-01-01
  • 2016-02-21
  • 2021-02-06
  • 2011-09-19
  • 2020-02-28
  • 1970-01-01
相关资源
最近更新 更多