parsing json with java parsing json with java json json

parsing json with java


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


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


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 548.8653612.329584Renaissance Paris Arc de Triomphe Hotel 548.8771072.297451