parsing json with java

南楼画角 提交于 2019-12-29 00:41:08

问题


I am a newbie to json parsing, I have grabbed a json string from a request and now I need to parse it with java. I'm using json-lib for this. But I'm really stuck as I'm not familiar with it. I need to extract following data

1. name (hotel name)
2. starRating
3. geoPoint

I used following java code for that but it's not giving me the result I need, please someone help me...

Thanks a lot!

java code (s is the json string I get)

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

json I need to parse

[
{
    "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
        }           
  ]         
}           
  ]

回答1:


Any JSON object can be represented as a Map<String, Object>.

Use a library like jackson (shipped with spring), which can deserialize json to a Map like this:

Map<String, Object> obj = new ObjectMapper().readValue(json, new TypeReference<Map<String, Object>>());

Or the slower, but google-branded, GSON, which can be used like.

Map<String, Object> obj = new Gson().fromJson(json, HashMap.class);



回答2:


To get past the ClassCastException, you just need to make the change it's telling you to make: to handle the input as an array and not as an object.

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

And, here's an example of getting each hotel name.

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



回答3:


I recommend Djson parser(java library). https://github.com/jungkoo/djson_parser

code:

Var hotels = Djson.parse(new File("d:\\sample1.txt")).find("[0].hotels");

for(int i=0; i<hotels.size(); i++) {            
  System.out.println(hotels.get(i).get("name").toString());
  System.out.println(hotels.get(i).get("starRating").toInt());
  System.out.println(hotels.get(i).find("geoPoint").get(0).toDouble()); // case1) basic
  System.out.println(hotels.get(i).find("geoPoint[1]").toDouble()); // case2) find()    
  System.out.println();
}

output:

Renaissance Paris Vendome Hotel 5
48.865361
2.329584

Renaissance Paris Arc de Triomphe Hotel 5
48.877107
2.297451



回答4:


Download the json-lib and Use JSONObject

Lets say {"name": "joe", "age": 33}

Do like this

JSONObject jobject=new JSONObject(jsonstring);
String name=jobject.getString("name");



回答5:


I have started a github project project called JsonQuery that makes this kind of thing easier.

The project is built on top of GSON.

If you wanted to retrieve the name of your hotel, for example, it could be as simple as this:

JsonQuery $ = JsonQuery.fromJson(s); 
$.val("hotels.name");

Here is the link:

https://github.com/rdbeach/JsonQuery



来源:https://stackoverflow.com/questions/6544389/parsing-json-with-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!