如何从Google Custom Search API创建JSON对象?

时间:2017-03-04 02:05:46

标签: java json google-api jackson

我正在努力寻找一种从我的Google Custom Search API查询中返回的JSON创建JSON对象的方法。我目前正在使用下面的代码执行搜索并将搜索查询的结果作为字符串返回:

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

如何使用Jackson 2将JSON解析为Java对象?我只是主要想保留图像链接和描述。我如何使用Jackson 2做到这一点?或者我需要使用其他东西吗?

我的JSON响应的一部分发布在下面(整个事情是巨大的):

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"
     }
    ],

2 个答案:

答案 0 :(得分:0)

  

如何使用Jackson 2将JSON解析为Java对象?

将JSON转换为Java对象:

这是一个如何完成任务的简单示例:

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

答案 1 :(得分:0)

如果您的需求非常具体,并且您不想将完整的JSON映射到POJO,那么您可以使用Jackson 2.3.0发行版中提供的JsonPointer。例如,检索

v.counter=2

请注意,所附代码未经过测试或编译,也不适合生产使用。它应该只作为一个例子。