我有一个json文件。
{
"data" : [
"my/path/old",
"my/path/new"
]
}
我需要将它转换为String的ArrayList。如何使用杰克逊图书馆?
UPD:
我的代码:
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);
答案 0 :(得分:4)
你已经标记了杰克逊,但在你的例子中使用了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);
获取名为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]