2

我正在使用 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”)在数组“项目”中。上面的代码从第一个数组“查询”开始,只向我发送名为“id”的 1 个元素,我不关心它。然后它会根据 while 语句停止解析,并且不会到达“items”数组。如何更改上面的代码以跳到我感兴趣的数组“项目”,以便获得所需的“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",
   ....
4

1 回答 1

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());
于 2013-01-18T04:03:44.643 回答