2017-03-04 1 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)를 사용하여 자바 객체로 JSON을 구문 분석 할 : 저는 현재 검색을 수행하고 String으로 검색 쿼리의 결과를 반환하도록 아래의 코드를 사용하고? 나는 주로 이미지 링크와 설명 만 유지하려고합니다. 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)를 사용하여 자바 객체로 JSON을 구문 분석합니까? 자바 객체에

변환 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