2017-03-04 133 views
0

我正努力从我的Google Custom Search 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); 
    } 

如何解析JSON使用杰克逊2 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" 
    } 
    ], 

回答

0

如何解析JSON使用杰克逊2 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); 
+0

'YourClassName'会是什么?我是否需要用为此设置的变量创建一个新类? – QQuestions

0

如果您需要的是非常具体的,你不希望映射完整的JSON到POJO,那么你可以使用杰克逊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