Pav*_*ara 4 java json json-lib
我是json解析的新手,我从请求中抓取了一个json字符串,现在我需要用java解析它.我正在使用json-lib.但我真的被困住了,因为我不熟悉它.我需要提取以下数据
1. name (hotel name)
2. starRating
3. geoPoint
Run Code Online (Sandbox Code Playgroud)
我使用了以下java代码,但它没有给我我需要的结果,请有人帮助我...
非常感谢!
java代码(s是我得到的json字符串)
JSONObject json = (JSONObject) JSONSerializer.toJSON(s);
JSONArray jarray = json.getJSONArray("hotels");
for(int i=0 ; i < jarray.size(); i++) {
System.out.println("jarray [" + i + "] --------" + jarray.getString(i));
}
Run Code Online (Sandbox Code Playgroud)
json我需要解析
[
{
"total": 250,
"offset": 0,
"requestID": "-btygi09oxfov",
"locationName": "Paris, France",
"locationLatitude": 48.86,
"locationLongitude": 2.34,
"cityCode": "PARIS_J_FR",
"hotels": [
{
"ypid": "YN10001x300073304",
"id": 56263,
"hotelRateIndicator": "2",
"name": "Renaissance Paris Vendome Hotel",
"brandCode": "69",
"addressLine1": "4 Rue du Mont-Thabor",
"city": "Paris",
"neighborhood": "",
"state": "IdF",
"country": "US",
"cachedPrice": 935,
"geoPoint": [
48.865361,
2.329584
],
"starRating": "5",
"thumbnailUrl": "http://www.orbitz.com//public/hotelthumbnails/53/97/85397/85397_TBNL_1246535840051.jpg",
"total": 250,
"amenities": [
"24",
"31",
"42",
"52",
"9"
],
"telephoneNumbers": [
""
],
"popularity": 837
},
{
"ypid": "YN10001x300073331",
"id": 112341,
"hotelRateIndicator": "3",
"name": "Renaissance Paris Arc de Triomphe Hotel",
"brandCode": "69",
"addressLine1": "39 Avenue de Wagram",
"city": "Paris",
"neighborhood": "",
"state": "IdF",
"country": "US",
"cachedPrice": 633,
"geoPoint": [
48.877107,
2.297451
],
"starRating": "5",
"thumbnailUrl": "http://www.orbitz.com//public/hotelthumbnails/21/72/302172/302172_TBNL_1246535872514.jpg",
"total": 250,
"amenities": [
"24",
"31",
"42",
"9"
],
"telephoneNumbers": [
""
],
"popularity": 796
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
任何JSON对象都可以表示为Map<String, Object>.
使用像jackson这样的库(随spring一起提供),它可以将json反序列化为Map,如下所示:
Map<String, Object> obj = new ObjectMapper().readValue(json, new TypeReference<Map<String, Object>>());
Run Code Online (Sandbox Code Playgroud)
Map<String, Object> obj = new Gson().fromJson(json, HashMap.class);
Run Code Online (Sandbox Code Playgroud)
要超越ClassCastException,您只需要进行更改,告诉您:将输入作为数组处理而不是作为对象处理.
JSONArray outerArray = (JSONArray) JSONSerializer.toJSON(s);
JSONObject json = (JSONObject) outerArray.get(0);
JSONArray jarray = json.getJSONArray("hotels");
for (int i = 0; i < jarray.size(); i++)
{
System.out.println("jarray [" + i + "] --------" + jarray.getString(i));
}
Run Code Online (Sandbox Code Playgroud)
并且,这是获取每个酒店名称的示例.
JSONArray outerArray = (JSONArray) JSONSerializer.toJSON(s);
JSONObject json = (JSONObject) outerArray.get(0);
JSONArray jarray = json.getJSONArray("hotels");
for (int i = 0; i < jarray.size(); i++)
{
JSONObject hotel = jarray.getJSONObject(i);
String name = hotel.getString("name");
System.out.println(name);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44394 次 |
| 最近记录: |