杰克逊解析特定阵列

时间:2013-01-18 02:34:03

标签: json parsing jackson

我正在使用杰克逊解析api结果,这似乎运作良好。

爪哇:

public static void jsonIn(String st){
         try {
        JsonFactory jfactory = new JsonFactory();
        /*** read from URL ***/
        JsonParser jParser = jfactory.createJsonParser(new URL(st));
        // loop until token equal to "}"
        while (jParser.nextToken() != JsonToken.END_ARRAY) {
            String fieldname = jParser.getCurrentName();
            if ("id".equals(fieldname)) {
              // current token is "id",
                      // move to next, which is "id"'s value
            try{
              jParser.nextToken();
                }
            catch (Exception e){

            }
              System.out.println(jParser.getText()); // display id
            }
          }
          jParser.close();
         } catch (JsonGenerationException e) {
          e.printStackTrace();
         } 

      }

问题:

然而 - 我想要的结果(字段:" id")在数组" items"中。上面的代码从第一个数组开始"查询"并且只向我发送名为" id"的1个元素,我不在乎。然后它停止基于while语句进行解析,并且没有到达"项目"阵列。如何更改上面的代码以跳到数组" items"我感兴趣的是这样我才能得到#34; id"我想要的字段?

JSON:

{
 "app": "Sale",
 "avail": {
  "type": "application/json",
},
 "queries": {
  "unAvailURIs": [
   {
    "id": "1sdf6gf3jf80dhb3",
    "results": "57",
    "searchTerms": "lycos.com",
    "startIndex": 11
   }
  ],
  "apiSource": [
   {
    "title": "go****y",
    "totalResults": "579000",
    "auctionPhrase": "lycos.com",
    "count": 10,
    "startIndex": 1,
    "id": "in",
   }
  ]
 },
 "pullAPI": {
  "search": "lycos.com"
 },
 "searchInformation": {
  "searchTime": 0.025345,
  "totalResults": "57600100",
 },
 "items": [
  {
   "id": "GD172993",
   "title": "lycos.com",
   ....

1 个答案:

答案 0 :(得分:4)

我似乎错过了我正在寻找的那篇SO帖子:Parsing JSON Bing results with Jackson。 感谢您@fge解释ObjectMapperreadTree() 我只是将我的顶级try语句的开头替换为:

try {    
    JsonFactory jfactory = new JsonFactory();
    JsonParser jParser = jfactory.createJsonParser(new URL(st));
    ObjectMapper mapper = new ObjectMapper();
    JsonNode input = mapper.readTree(jParser);
    final JsonNode results = input.get("items");
    // loop until token equal to "}"
    for (final JsonNode element: results) {
        JsonNode fieldname = element.get("id");
        System.out.println(fieldname.toString());