2017-03-04 11 views
0

私は、Googleカスタム検索APIクエリから返されたJSONからJSONオブジェクトを作成する方法を見つけるのに苦労しています。私は現在、検索を実行し、文字列として検索クエリの結果を返すために以下のコードを使用しています:Googleカスタム検索APIから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); 
    } 

私はジャクソン2を使用してJavaオブジェクトにJSONを解析する方法を教えてください。私は主に画像のリンクと説明を保持したいだけです。 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" 
    } 
    ], 

答えて

0

私はジャクソン2を使用してJavaオブジェクトにJSONを解析する方法を教えてください。

Javaオブジェクトに変換するJSON:ここ

は、あなたのタスクを達成する方法の簡単な例です:

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

「YourClassName」は何ですか?このために変数を設定して新しいクラスを作成する必要がありますか? – QQuestions

0

あなたの必要性は非常に特殊であり、あなたがマッピングしたくない場合完全なJSONをPOJOに渡すと、Jackson 2.3.0リリースで利用可能なJsonPointerを使用することができます。

final String ITEMS = "/items"; 
final String PRD_IMG = "/product/image"; 
final String PRD_DESC = "/product/description"; 

ObjectMapper mapper = new ObjectMapper(); 
JsonNode root = mapper.readTree(url); 

JsonPointer ptr = JsonPointer.compile(ITEMS); 
JsonPointer ptrImage = JsonPointer.compile(PRD_IMG); 
JsonPointer ptrDesc = JsonPointer.compile(PRD_DESC); 

JsonNode itemsRoot = root.at(ptr); 

if (itemsRoot.isArray()) { 
    JsonNode[] items = itemsRoot.elements(); 
    for(JsonNode itemRoot : items) { 
    String image = itemRoot.path(ptrImage).textValue(); 
    String desc = itemRoot.path(ptrDesc).textValue(); 
    } 
} 

を取得するために、例えば、添付のコードがテストされていないか、コンパイルされ、どちらも生産使用のために意図されていないことに注意してください。それは例としてとるべきです。

+0

JsonNode [] items = itemsRoot.elements(); は互換性のない型エラーを返しますか?あなたはどうしてその理由を知っていますか? – QQuestions

関連する問題