如何在java中处理JSON响应

时间:2013-12-05 09:26:43

标签: java json rest

我需要处理json响应,它是通过休息服务GET方法调用来实现的。     我已经看过这些链接的解决方案: -

http://www.journaldev.com/2315/java-json-processing-api-example-tutorial

http://answers.oreilly.com/topic/257-how-to-parse-json-in-java/

但它不符合我的要求,因为它小而且静态。我在下面保留我的json响应: -

`<!--json response start -->

   {
    "HotelListResponse": {
        "cachedSupplierResponse": {
            "@cachedTime": "0",
            "@candidatePreptime": "111",
            "@matchedCurrency": "true",
            "@matchedLocale": "true",
            "@otherOverheadTime": "4",
            "@supplierRequestNum": "211",
            "@supplierResponseNum": "20",
            "@supplierResponseTime": "405",
            "@tpidUsed": "5001"
        },
        "cacheKey": "302c317:13443ffb599:-7712",
        "cacheLocation": "10.186.168.61:7302",
        "customerSessionId": "0ABAA83D-2C31-7913-4432-FFB599907714",
         "HotelList": {
            "@activePropertyCount": "237",
            "@size": "1",
            "HotelSummary": {
                "@ubsScore": "1867",
                "@order": "0",
                "hotelId": 127092,
                "name": "The Edgewater - A Noble House Hotel",
                "address1": "Pier 67, 2411 Alaskan Way",
                "city": "Seattle",
                "stateProvinceCode": "WA",
                "postalCode": 98121,
                "countryCode": "US",
                "airportCode": "SEA",
                "supplierType": "E",
                "propertyCategory": 1,
                "hotelRating": 4,
                "confidenceRating": 85,
                "amenityMask": 6259019,
                "tripAdvisorRating": 4,
                "tripAdvisorReviewCount": 590,
                "tripAdvisorRatingUrl": "http://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/4.0-12345-4.gif",
                "locationDescription": "Near Washington State Convention & Trade Center",
                "shortDescription": "<p><b>Location. </b> <br />The Edgewater - A Noble House Hotel is a business-friendly hotel located in central Seattle, close to Odyssey - The Maritime Discovery Center, Washington State Convention &",
                "highRate": 249,
                "lowRate": 186.75,
                "rateCurrencyCode": "USD",
                "latitude": 47.61252,
                "longitude": -122.35013,
                "proximityDistance": 11.898841,
                "proximityUnit": "MI",
                "hotelInDestination": true,
                "thumbNailUrl": "/hotels/1000000/20000/11200/11133/11133_73_t.jpg",
                "deepLink": "http://travel.ian.com/index.jsp?pageName=hotAvail&cid=55505&hotelID=127092&mode=2&numberOfRooms=2&room-0-adult-total=1&room-0-child-total=1&room-0-child-0-age=3&room-1-adult-total=1&room-1-child-total=1&room-1-child-0-age=5&arrivalMonth=8&arrivalDay=4&departureMonth=8&departureDay=5&showInfo=true&locale=en_US&currencyCode=USD",
                "RoomRateDetailsList": {
                    "RoomRateDetails": {
                        "roomTypeCode": 1160,
                        "rateCode": 1221260,
                        "maxRoomOccupancy": 2,
                        "quotedRoomOccupancy": 2,
                        "minGuestAge": 0,
                        "roomDescription": "City Lodge - Nonrefundable",
                        "promoId": 200803780,
                        "promoDescription": "7-Day Advance Purchase Special (Nonrefundable)",
                        "currentAllotment": 10,
                        "propertyAvailable": true,
                        "propertyRestricted": false,
                        "expediaPropertyId": 11133,
                        "rateKey": "f3525aff-9f4d-4d92-bc1c-144628fcaa30",
                        "nonRefundable": true,
                        "RateInfos": {
                            "@size": "1",
                            "RateInfo": {
                                "@rateChange": "false",
                                "@promo": "true",
                                "@priceBreakdown": "true",
                                "RoomGroup": {
                                    "Room": [
                                        {
                                            "numberOfAdults": 1,
                                            "numberOfChildren": 1,
                                            "childAges": 3
                                        },
                                        {
                                            "numberOfAdults": 1,
                                            "numberOfChildren": 1,
                                            "childAges": 5
                                        }
                                    ]
                                },
                                "ChargeableRateInfo": {
                                    "@commissionableUsdTotal": "373.5",
                                    "@total": "441.74",
                                    "@surchargeTotal": "68.24",
                                    "@nightlyRateTotal": "373.5",
                                    "@averageBaseRate": "249.0",
                                    "@averageRate": "186.75",
                                    "@maxNightlyRate": "186.75",
                                    "@currencyCode": "USD",
                                    "NightlyRatesPerRoom": {
                                        "@size": "1",
                                        "NightlyRate": {
                                            "@promo": "true",
                                            "@rate": "186.75",
                                            "@baseRate": "249.0"
                                        }
                                    },
                                    "Surcharges": {
                                        "@size": "1",
                                        "Surcharge": {
                                            "@amount": "68.24",
                                            "@type": "TaxAndServiceFee"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
  

所以我在这里得到基于我的休息网址调用的动态响应,所以如何将这个json响应设置为我的pojo。

任何帮助将不胜感激。

提前谢谢你。 `

3 个答案:

答案 0 :(得分:0)

您可以使用框架来处理所有这些;一个伟大的是春天。 看看here 这是stackoverflow question让你快速入门。

上面的链接示例:

创建一个Controller来处理REST调用(更改为演示json使用):

@Controller
@RequestMapping("/kfc/brands")
public class JSONController {

    @RequestMapping(value="{name}", method = RequestMethod.POST)
    public @ResponseBody Shop getShopInJSON(@PathVariable String name, @RequestBody JsonNode json) {
        // do stuff with the json request body (its is jackson)
        JsonNode test= json.get("test");

        Shop shop = new Shop();
        shop.setName(name);
        shop.setStaffName(new String[]{"mkyong1", "mkyong2"});

        return shop;

    }
}

// you could use jQuery to perform a REST call to your new controller:
$.ajax({
    type: "POST",
    url: "[your server]/kfc/brands",
    data: {"test": "json value"},
    success: function() {}
});

答案 1 :(得分:0)

尝试gson lib。它将 json 转换为 pojo ,将 pojo 转换为 json

答案 2 :(得分:0)

如果您有JSON响应的架构,那么jsonschema2pojo将是一个很好的工具。它的工作方式类似于JAXB为XML所做的工作,因为它在构建时基于模式生成pojos,然后您可以在编译时使用它。

如果没有架构但您对格式有信心,则可以始终generate the schema yourself