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

时间:2013-08-22 18:50:14

标签: java json parsing getjson

我有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"
                            }
                        }
                    }
                }
            }
        }
    }
}

3 个答案:

答案 0 :(得分:4)

我知道在Java中解析JSON有两个库:GSON和Jackson。我对杰克逊有一点了解,它有三种方式:

  1. 您可以让Jackson将您的JSON解析为对象
  2. 您可以阅读JSON并将其加载到内存中,以便可以在其中导航。
  3. 您可以像流一样阅读JSON
  4. 以下是有关这些方式的链接:http://wiki.fasterxml.com/JacksonInFiveMinutes

答案 1 :(得分:1)

我会使用一个库,比如http://json-lib.sourceforge.net/(其他人就在那里;这只是我在网络搜索中发现的第一个。)

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

答案 2 :(得分:0)

我总结并使用了杰克逊 这是一个答案,也许对其他人有用

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

    }