我有一个类似的JSON文件:
{"city":[
{
"id":"c1",
"name":"Paris",
"population":2125851,
"département":"075"
},
{
"id":"c2",
"name":"Marseille",
"population":797491,
"département":"013"
}],"person":[
{
"id":"p1",
"name":"Jules Verne",
"born":"c6",
"category":"cat3",
"birthdate":"1828-02-08"
},
{
"id":"p2",
"name":"René Coty",
"born":"c11",
"category":"cat2",
"birthdate":"1882-03-20"
}]}
我需要提取对象名称,所以我需要到达这里" city"和"人"。 我和杰克逊试过这样的事情:
JsonParser jParser = null;
JsonFactory jfactory = new JsonFactory();
jParser = jfactory.createJsonParser(new File("graph.gjson"));
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
jParser.nextToken();
System.out.println(jParser.getText());
但这不起作用,任何人都可以帮助我吗?
答案 0 :(得分:1)
我刚刚找到解决方案
Object obj;
try {
obj = parser.parse(new FileReader(json));
JSONObject jsonObject = (JSONObject) obj;
Set<String> keys = jsonObject.keySet();
java.util.Iterator<String> key= keys.iterator();
while(key.hasNext())
{ Object element = key.next();
System.out.println(element);
}
} catch (IOException | org.json.simple.parser.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我想与你分享那些会像我一样搜索同样事物的人,所以这里的输出就是对象名称“key”,它们是城市和人。
答案 1 :(得分:0)
答案 2 :(得分:0)
如果您不想将JSON转换为POJO,可能需要查看JsonPath,只想从中提取一些值:
public static void main(String[] args) {
final String json = ...;
final List<String> personNames = JsonPath.read(json, "$.person[*].name");
final List<String> cityNames = JsonPath.read(json, "$.city[*].name");
System.out.println(personNames);
System.out.println(cityNames);
}