我有一个 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):
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);
最佳答案
您已标记 Jackson,但在示例中使用 Gson。我要和 jackson 一起去
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);
获取JsonNode
命名data
JsonNode arrayNode = node.get("data");
将其解析为ArrayList<String>
ArrayList<String> data = mapper.readValue(arrayNode.traverse(), new TypeReference<ArrayList<String>>(){});
打印
System.out.println(data);
给出
[my/path/old, my/path/new]
关于java - 如何将 JSON 解析为字符串列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22873521/