How do I create a JSON object from the Google Custom Search API?

advertisements

I am struggling to find a way to create a JSON Object from the returned JSON from my Google Custom Search API query. I am currently using the code below to perform a search and return the results of the search query as a String:

    URL url = new URL(
            "https://www.googleapis.com/customsearch/v1?key=" + key + "&cx=" + cx + "&q=" + qry + "&alt=json&queriefields=queries(request(totalResults))");

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");
    BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

How do I parse the JSON to a Java Object using Jackson 2? I only mainly want to keep the image links and the descriptions. How do I do this using Jackson 2? Or do I need to use something else?

Part of my JSON response is posted below (the whole thing is huge):

Output from Server .... 

{
 "kind": "customsearch#search",
 "url": {
  "type": "application/json",
  "template": "https://www.googleapis.com/customsearch/v1?q={searchTerms}&num={count?}&start={startIndex?}&lr={language?}&safe={safe?}&cx={cx?}&cref={cref?}&sort={sort?}&filter={filter?}&gl={gl?}&cr={cr?}&googlehost={googleHost?}&c2coff={disableCnTwTranslation?}&hq={hq?}&hl={hl?}&siteSearch={siteSearch?}&siteSearchFilter={siteSearchFilter?}&exactTerms={exactTerms?}&excludeTerms={excludeTerms?}&linkSite={linkSite?}&orTerms={orTerms?}&relatedSite={relatedSite?}&dateRestrict={dateRestrict?}&lowRange={lowRange?}&highRange={highRange?}&searchType={searchType}&fileType={fileType?}&rights={rights?}&imgSize={imgSize?}&imgType={imgType?}&imgColorType={imgColorType?}&imgDominantColor={imgDominantColor?}&alt=json"
 },
 "queries": {
  "request": [
   {
    "title": "Google Custom Search - unpaired\"white\"adidas\"superstar",
    "totalResults": "134",
    "searchTerms": "unpaired\"white\"adidas\"superstar",
    "count": 10,
    "startIndex": 1,
    "inputEncoding": "utf8",
    "outputEncoding": "utf8",
    "safe": "off",
    "cx": "003266051393521274164:ofe8peg9ktm"
   }
  ],
  "nextPage": [
   {
    "title": "Google Custom Search - unpaired\"white\"adidas\"superstar",
    "totalResults": "134",
    "searchTerms": "unpaired\"white\"adidas\"superstar",
    "count": 10,
    "startIndex": 11,
    "inputEncoding": "utf8",
    "outputEncoding": "utf8",
    "safe": "off",
    "cx": "003266051393521274164:ofe8peg9ktm"
   }
  ]
 },
 "context": {
  "title": "SearchEngine"
 },
 "searchInformation": {
  "searchTime": 0.565907,
  "formattedSearchTime": "0.57",
  "totalResults": "134",
  "formattedTotalResults": "134"
 },
 "items": [
  {
   "kind": "customsearch#result",
   "title": "adidas Superstar Foundation Shoes - White | adidas US",
   "htmlTitle": "\u003cb\u003eadidas Superstar\u003c/b\u003e Foundation Shoes - \u003cb\u003eWhite\u003c/b\u003e | adidas US",
   "link": "http://www.adidas.com/us/superstar-foundation-shoes/B27136.html",
   "displayLink": "www.adidas.com",
   "snippet": "Shop the Superstar Foundation Shoes - White at adidas.com/us! See all the \nstyles and colors of Superstar Foundation Shoes - White at the official adidas \nonline ...",
   "htmlSnippet": "Shop the \u003cb\u003eSuperstar\u003c/b\u003e Foundation Shoes - \u003cb\u003eWhite\u003c/b\u003e at \u003cb\u003eadidas\u003c/b\u003e.com/us! See all the \u003cbr\u003e\nstyles and colors of \u003cb\u003eSuperstar\u003c/b\u003e Foundation Shoes - \u003cb\u003eWhite\u003c/b\u003e at the official \u003cb\u003eadidas\u003c/b\u003e \u003cbr\u003e\nonline ...",
   "cacheId": "yYdqTcWb_rQJ",
   "formattedUrl": "www.adidas.com/us/superstar-foundation-shoes/B27136.html",
   "htmlFormattedUrl": "www.\u003cb\u003eadidas\u003c/b\u003e.com/us/\u003cb\u003esuperstar\u003c/b\u003e-foundation-shoes/B27136.html",
   "pagemap": {
    "offer": [
     {
      "price": "USD 80.00",
      "pricecurrency": "USD",
      "itemcondition": "http://schema.org/NewCondition",
      "availability": "http://schema.org/InStock"
     },
     {
      "pricecurrency": "USD",
      "itemcondition": "http://schema.org/NewCondition",
      "price": "80",
      "availability": "http://schema.org/InStock"
     }
    ],
    "cse_thumbnail": [
     {
      "width": "225",
      "height": "225",
      "src": "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQy1NkJHvjHngC582YRzHalmQpL0Vh1lQ-OwumaJA58tyg-EAremAlklsk"
     }
    ],
    "product": [
     {
      "brand": "adidas",
      "color": "White",
      "model": "IKG83",
      "name": "Superstar Foundation Shoes",
      "potentialaction": "customize",
      "category": "custom shoes",
      "image": "http://demandware.edgesuite.net/sits_pod20-adidas/dw/image/v2/aaqx_prd/on/demandware.static/-/Sites-adidas-products/en_US/dw447f6af6/zoom/B27136_01_standard.jpg?sw=500&sfrm=jpg",
      "description": "These shoes honor the clean simplicity and premium materials of the original adidas Superstar sneaker with a full grain leather upper and signature rubber shell toe. Finished with a herringbone-pat..."
     }
    ],
    "breadcrumb": [
     {
      "url": "Home",
      "title": "Home"
     },
     {
      "url": "Men",
      "title": "Men"
     },
     {
      "url": "Shoes",
      "title": "Shoes"
     }
    ],
    "review": [
     {
      "reviewer": "MariArias",
      "reviewdate": "2017-02-25",
      "ratingstars": "5.0"
     },
     {
      "name": "Best ever",
      "datepublished": "2017-02-25",
      "description": "I love these shoes. I had a slight problem with my order, but customer service took care of it in a timely manner. Thank you Adidas! I suggest this product to anyone who likes to look lit.",
      "author": "MariArias"
     },
     {
      "name": "Very nice shoes",
      "datepublished": "2017-02-27",
      "description": "These shoes were beyond comfortable. They were the perfect size and did not crush or cause any discomfort on my feet. I would recommend this to anyone looking for good-looking, nice shoes....",
      "author": "Maia03"
     },
     {
      "name": "Why ruin an icon!!!",
      "datepublished": "2017-02-22",
      "description": "Made so cheap! Embarrassing to wear. Cheap plastic looking leather and cheap rubber. Glue everywhere. Can't even print letting right look at the S and the T. Several years ago (to me) this...",
      "author": "Aaron75"
     },
     {
      "name": "Classiest shoes ever",
      "datepublished": "2017-02-06",
      "description": "My brother is obsessed with leather of a specific type. After seeing these shoes he loved the leather of the superstar shoes as that's the type of leather he likes!",
      "author": "Kay96"
     },
     {
      "datepublished": "2017-01-08",
      "description": "This product is amazing quality, stylish and comfortable all for very affordable price. Love the colour and the style. Absolutely made up with my purchase. Highly recommend this style of trainer",
      "author": "bigDderek"
     },
     {
      "name": "Best sneaker ever....",
      "datepublished": "2017-02-22",
      "description": "Best sneaker ever...clean classic look....easy to keep clean",
      "author": "Buckxx15"
     },
     {
      "datepublished": "2017-02-14",
      "description": "Easy to purchase on line - product was exactly what I saw in the stores, very comfortable! Love them!",
      "author": "smile13"
     },
     {
      "name": "Very happy with service we received and product",
      "datepublished": "2017-02-19",
      "description": "My daughter has the white but wanted the black uses shoe very much",
      "author": "Tamsy"
     },
     {
      "name": "looks nice, comfortable and i would recommend to a friend",
      "datepublished": "2017-01-14",
      "description": "got them for my girlfriend she thought it was comfortable however felt it was a little bit uncomfortable at the end of the shoe, but overall it was a perfect Christmas present for her.",
      "author": "mally45092"
     },
     {
      "name": "A",
      "datepublished": "2017-02-17",
      "description": "These were to small so sent back and ordered a size bigger",
      "author": "BLEE"
     }
    ],
    "rating": [
     {
      "ratingvalue": "5",
      "bestrating": "5"
     },
     {
      "ratingvalue": "5",
      "bestrating": "5"
     },
     {
      "ratingvalue": "1",
      "bestrating": "5"
     },
     {
      "ratingvalue": "5",
      "bestrating": "5"
     },
     {
      "ratingvalue": "4",
      "bestrating": "5"
     },
     {
      "ratingvalue": "5",
      "bestrating": "5"
     },
     {
      "ratingvalue": "4",
      "bestrating": "5"
     },
     {
      "ratingvalue": "4",
      "bestrating": "5"
     },
     {
      "ratingvalue": "5",
      "bestrating": "5"
     },
     {
      "ratingvalue": "3",
      "bestrating": "5"
     }
    ],
    "metatags": [
     {
      "og:image": "http://demandware.edgesuite.net/aaqx_prd/on/demandware.static/-/Sites-adidas-products/en_US/dw447f6af6/zoom/B27136_01_standard.jpg",
      "og:type": "product",
      "og:site_name": "adidas United States",
      "og:title": "adidas Superstar Foundation Shoes - White | adidas US",
      "fb:admins": "100002410377144",
      "og:url": "http://www.adidas.com/us/superstar-foundation-shoes/B27136.html",
      "og:description": "These shoes honor the clean simplicity and premium materials of the original adidas Superstar sneaker with a full grain leather upper and signature rubber shell toe. Finished with a herringbone-pattern rubber cupsole and a printed Trefoil logo on the heel.",
      "msapplication-config": "http://demandware.edgesuite.net/aaqx_prd/on/demandware.static/Sites-adidas-US-Site/-/default/dw8ca2de91/images/favicons/browserconfig.xml",
      "theme-color": "#fff",
      "fb:app_id": "129087217170262",
      "format-detection": "telephone=no",
      "twitter:card": "product",
      "twitter:site": "null",
      "twitter:creator": "@adidas",
      "twitter:title": "Superstar Foundation Shoes",
      "twitter:label1": "Availability",
      "twitter:data1": "In Stock",
      "twitter:data2": "United States",
      "twitter:label2": "Country:",
      "twitter:image": "http://demandware.edgesuite.net/sits_pod20-adidas/dw/image/v2/aaqx_prd/on/demandware.static/-/Sites-adidas-products/en_US/dw447f6af6/zoom/B27136_01_standard.jpg?sw=500&sfrm=jpg"
     }
    ],
    "cse_image": [
     {
      "src": "http://demandware.edgesuite.net/aaqx_prd/on/demandware.static/-/Sites-adidas-products/en_US/dw447f6af6/zoom/B27136_01_standard.jpg"
     }
    ],


How do I parse the JSON to a Java Object using Jackson 2?

Convert JSON to Java object:

here is a quick example of how to accomplish your task:

ObjectMapper objMapper = new ObjectMapper();
String myJson = "{'name' : 'tester'}"; // assuming this is your JSON data

//JSON from URL to Object
YourClassName obj = objMapper.readValue(new URL("http://testing.com/api/staff.json"), YourClassName.class);

//JSON from String to Object
YourClassName obj = objMapper.readValue(myJson, YourClassName.class);