用java解析json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6544389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:38:19  来源:igfitidea点击:

parsing json with java

javajsonjson-lib

提问by Pavithra Gunasekara

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

我是 json 解析的新手,我从请求中获取了一个 json 字符串,现在我需要用 java 解析它。我为此使用 json-lib。但我真的很困惑,因为我不熟悉它。我需要提取以下数据

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...

我为此使用了以下 java 代码,但它没有给我我需要的结果,请有人帮助我...

Thanks a lot!

非常感谢!

java code (s is the json string I get)

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

json I need to parse

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
        }           
  ]         
}           
  ]

回答by Bohemian

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

任何 JSON 对象都可以表示为Map<String, Object>.

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

使用像Hymanson这样的库(与 spring 一起提供),它可以像这样将 json 反序列化为 Map:

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.

或者更慢但谷歌品牌的GSON,可以像这样使用。

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

回答by Programmer Bruce

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.

要克服 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));
}

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

回答by tost

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

我推荐 Djson 解析器(java 库)。 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

回答by Fizer Khan

Download the json-liband Use JSONObject

下载json-lib并使用JSONObject

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

可以说 {"name": "joe", "age": 33}

Do like this

这样做

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

回答by rdbeach

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

我已经启动了一个名为 JsonQuery 的 github 项目项目,它使这种事情变得更容易。

The project is built on top of GSON.

该项目建立在 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://github.com/rdbeach/JsonQuery