解析 JSON 字符串 java,最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18388593/
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-12 01:07:15  来源:igfitidea点击:

parse JSON string java, best practice

javajsonparsinggetjson

提问by Armen Arzumanyan

I have JSON string/response and I need simple parse it and get objects/arrays, it can be repeated, so I need get list by list, actually I do not know how to do it, because a lot of parsers and all examples with simple JSON-es, but my is bit difficult and I need to navigate in it. Here is a example of my JSON

我有 JSON 字符串/响应,我需要简单解析它并获取对象/数组,它可以重复,所以我需要按列表获取列表,实际上我不知道该怎么做,因为很多解析器和所有示例都带有简单的 JSON-es,但我的有点困难,我需要在其中导航。这是我的 JSON 示例

{
    "HotelListResponse": {
        "customerSessionId": "0ABAAA83-04C7-5B91-40A2-754D7299476C",
        "numberOfRoomsRequested": 1,
        "moreResultsAvailable": true,
        "cacheKey": "-4804c75b:140a754d729:4da2",
        "cacheLocation": "10.186.170.131:7300",
        "HotelList": {
            "@activePropertyCount": "1157",
            "@size": "1",
            "HotelSummary": {
                "@order": "0",
                "hotelId": 403147,
                "name": "Justabed - Hostel",
                "address1": "38 avenue augustin dumont",
                "city": "Malakoff",
                "postalCode": 92240,
                "countryCode": "FR",
                "airportCode": "   ",
                "supplierType": "E",
                "propertyCategory": 5,
                "hotelRating": 0,
                "confidenceRating": 52,
                "amenityMask": 8,
                "tripAdvisorRating": 1.5,
                "locationDescription": "Near Paris Expo Porte de Versailles",
                "shortDescription": "<p><b>Property Location</b> <br />With a stay at Justabed in Vanves, you'll be close to Stade de la Plaine and Eiffel Tower.<br/> This hostel is within close proximity of Georges Brassens Park and",
                "highRate": 24.87,
                "lowRate": 24.87,
                "rateCurrencyCode": "EUR",
                "latitude": 48.81804,
                "longitude": 2.30196,
                "proximityDistance": 2.5680416,
                "proximityUnit": "MI",
                "hotelInDestination": true,
                "thumbNailUrl": "/hotels/5000000/4850000/4849100/4849100/4849100_7_t.jpg",
                "deepLink": "http://travel.ian.com/index.jsp?pageName=hotAvail&cid=55505&hotelID=403147&mode=2&numberOfRooms=1&room-0-adult-total=1&room-0-child-total=0&arrivalMonth=8&arrivalDay=18&departureMonth=8&departureDay=21&showInfo=true&locale=en_US&currencyCode=EUR",
                "RoomRateDetailsList": {
                    "RoomRateDetails": {
                        "roomTypeCode": 200166353,
                        "rateCode": 201887482,
                        "maxRoomOccupancy": 1,
                        "quotedRoomOccupancy": 1,
                        "minGuestAge": 3,
                        "roomDescription": "Single Beds in Mixed Dormitory Room - Non refundable",
                        "currentAllotment": 8,
                        "propertyAvailable": true,
                        "propertyRestricted": false,
                        "expediaPropertyId": 4849100,
                        "rateKey": "0ABAAA83-04C7-5B91-40A2-754D72994DA3",
                        "RateInfo": {
                            "@rateChange": "false",
                            "@promo": "false",
                            "@priceBreakdown": "true",
                            "ChargeableRateInfo": {
                                "@total": "79.83",
                                "@surchargeTotal": "5.22",
                                "@nightlyRateTotal": "74.61",
                                "@maxNightlyRate": "24.87",
                                "@currencyCode": "EUR",
                                "@commissionableUsdTotal": "99.65",
                                "@averageRate": "24.87",
                                "@averageBaseRate": "24.87",
                                "NightlyRatesPerRoom": {
                                    "@size": "3",
                                    "NightlyRate": [
                                        {
                                            "@promo": "false",
                                            "@rate": "24.87",
                                            "@baseRate": "24.87"
                                        },
                                        {
                                            "@promo": "false",
                                            "@rate": "24.87",
                                            "@baseRate": "24.87"
                                        },
                                        {
                                            "@promo": "false",
                                            "@rate": "24.87",
                                            "@baseRate": "24.87"
                                        }
                                    ]
                                },
                                "Surcharges": {
                                    "@size": "1",
                                    "Surcharge": {
                                        "@amount": "5.22",
                                        "@type": "TaxAndServiceFee"
                                    }
                                }
                            }
                        },
                        "ValueAdds": {
                            "@size": "1",
                            "ValueAdd": {
                                "@id": "2048",
                                "description": "Free Wireless Internet"
                            }
                        }
                    }
                }
            }
        }
    }
}

采纳答案by Armen Arzumanyan

I summarized and used Hymanson here is a answer, maybe it will usefull for another people

我在这里总结并使用了 Hymanson 是一个答案,也许它对其他人有用

 public void parseLink(String jsonObject) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonFactory factory = mapper.getJsonFactory(); // since 2.1 use mapper.getFactory() instead
            JsonParser jp = factory.createJsonParser(jsonObject);
            JsonNode input = mapper.readTree(jp);

         //   final JsonNode results = input.get("HotelListResponse").get("HotelList").get("HotelSummary");

            Iterator<Entry<String, JsonNode>> nodeIterator = input.get("HotelListResponse").getFields();

            while (nodeIterator.hasNext()) {
                Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodeIterator.next();
                System.out.println("key --> " + entry.getKey() + " value-->" + entry.getValue());

            }

           Iterator<Entry<String, JsonNode>> nodeIterator1 = input.get("HotelListResponse").get("HotelList").getFields();

            while (nodeIterator1.hasNext()) {
                Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodeIterator1.next();
                System.out.println("key --> " + entry.getKey() + " value-->" + entry.getValue());

            }

            Iterator<Entry<String, JsonNode>> nodeIterator2 = input.get("HotelListResponse").get("HotelList").get("HotelSummary").getFields();

            while (nodeIterator2.hasNext()) {
                Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodeIterator2.next();
                System.out.println("key --> " + entry.getKey() + " value-->" + entry.getValue());

            }




        } catch (IOException ex) {
            Logger.getLogger(HotelBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

回答by dcsohl

I'd use a library for this, something like http://json-lib.sourceforge.net/(others are out there; that's just the first one I found with a web search.)

我会为此使用一个库,例如http://json-lib.sourceforge.net/(其他人在那里;这只是我通过网络搜索找到的第一个。)

Unless of course, this is a school project or something and you need to write your own parser. In that case, perhaps you should come up with a more specific question and ask that instead of asking how to do everything.

当然,除非这是一个学校项目或其他什么,并且您需要编写自己的解析器。在这种情况下,也许您应该提出一个更具体的问题并提出这个问题,而不是询问如何做所有事情。

回答by Maxime

There are 2 libraries that I know for parsing JSON in Java : GSON and Hymanson. I know a little about Hymanson and it works in 3 ways :

我知道有 2 个库可用于在 Java 中解析 JSON:GSON 和 Hymanson。我对Hyman逊有一点了解,它以三种方式起作用:

  1. You can ask Hymanson to parse your JSON into an object
  2. You can read your JSON and load it in memory, so you can navigate in it.
  3. You can read your JSON like a stream
  1. 你可以让 Hymanson 把你的 JSON 解析成一个对象
  2. 您可以读取您的 JSON 并将其加载到内存中,以便您可以在其中导航。
  3. 您可以像流一样读取 JSON

Here is the link about these ways : http://wiki.fasterxml.com/HymansonInFiveMinutes

这是有关这些方式的链接:http: //wiki.fasterxml.com/HymansonInFiveMinutes