2

I am using Jackson to parse api results and this seems to be working well.

Java:

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();
         } 

      }

Question:

However- the results that I want (field: "id") are in the array "items". The code above starts at the first array "queries" and only sends me the 1 element named "id", which I don't care for. It then stops parsing based on the while statement and doesnt get to the "items" array. How can I change my code above to skip to the array "items" that I am interested in so that I can get the "id" fields that I want?

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 Answer 1

4

I seem to have missed the one SO post I was looking for: Parsing JSON Bing results with Jackson. Thank you to @fge for explaining ObjectMapper and readTree().
I simply replaced the beginning of my top try statement as so:

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.