Java 如何将 JSON 解析为字符串列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22873521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse JSON to list of strings?
提问by Flavio
I have a json file.
我有一个 json 文件。
{
"data" : [
"my/path/old",
"my/path/new"
]
}
I need to conver it to ArrayList of String. How to do it using Hymanson library?
我需要将它转换为 String 的 ArrayList。如何使用Hyman逊图书馆做到这一点?
UPD:
更新:
My code:
我的代码:
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);
}
And my exception:
而我的例外:
Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 1
My new update
我的新更新
UPD2:
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);
采纳答案by Sotirios Delimanolis
You've tagged Hymanson but are using Gson in your example. I'm going to go with Hymanson
您已经标记了 Hymanson,但在您的示例中使用了 Gson。我要和Hyman逊一起去
String json = "{\"data\":[\"my/path/old\",\"my/path/new\"]}"; // or wherever you're getting it from
Create your ObjectMapper
创建您的 ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Read the JSON String as a tree. Since we know it's an object, you can cast the JsonNode
to an ObjectNode
.
将 JSON 字符串作为树读取。由于我们知道它是一个对象,因此您可以将JsonNode
转换为ObjectNode
。
ObjectNode node = (ObjectNode)mapper.readTree(json);
Get the JsonNode
named data
获取JsonNode
命名data
JsonNode arrayNode = node.get("data");
Parse it into an ArrayList<String>
将其解析为 ArrayList<String>
ArrayList<String> data = mapper.readValue(arrayNode.traverse(), new TypeReference<ArrayList<String>>(){});
Printing it
打印它
System.out.println(data);
gives
给
[my/path/old, my/path/new]