使用jackson和java获取json文件包含的对象

时间:2017-02-21 14:13:57

标签: java json jackson

我有一个类似的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());

但这不起作用,任何人都可以帮助我吗?

3 个答案:

答案 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)

将while循环条件更新为while(jParser.nextToken()!= JsonToken.END_ARRAY)这将让您解析整个数组而不仅仅是单个对象 更新解析所有内容的更通用解决方案     JsonToken token = jParser.nextToken();     while(令牌!= null&amp;&amp; token!= JsonToken.END_OBJECT)     {         String fieldname = jParser.getCurrentName();         if(fieldname!= null)         {             token = jParser.nextToken();             的System.out.println(jParser.getText());         }         token = jParser.nextToken();         if(token == JsonToken.END_OBJECT)             token = jParser.nextToken();     }

答案 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);
}