parsing json with java

淺唱寂寞╮ 提交于 2019-11-28 12:37:08

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 5
48.865361
2.329584

Renaissance Paris Arc de Triomphe Hotel 5
48.877107
2.297451

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

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

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