How to handle JSON response in java - java

I have requirement to handle json response and it is coming by rest service GET Method call.
I already have looked solutions from these links:-
http://www.journaldev.com/2315/java-json-processing-api-example-tutorial
http://answers.oreilly.com/topic/257-how-to-parse-json-in-java/
but it is not fulfill my requirements because it is small and static. I am keeping my json response in below:-
`<!--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"
}
}
}
}
}
}
}
}
}
}
}
so here I am getting dynamic response based on my rest url call so how do I set this json response to my pojo.
any help would be appreciated.
Thank you in advance.
`

You could use a framework to handle all that for you; a great one is Spring.
Have a look here
Here is stackoverflow question to get you jump-started.
example from link above:
create a Controller to handle REST calls (changed to demonstrate json use):
#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() {}
});

Try gson lib. It converts json to pojo and pojo to json.

If you have a schema for the JSON response then jsonschema2pojo would be a good tool to use. It works in a similar way that JAXB does for XML, in that it generates pojos at build time based on the schema, which you can then use at compile time.
If there isn't a schema but you are confident on the format, you could always generate the schema yourself.

Related

Is it possible to create dynamic pojo class according dynamic json response everytime?

An api provides different result in json everytime I hit. How can I generate a new model class everytime according to json response?
Is it possible to create dynamic pojo class according dynamic json response everytime??
on 1st hit -
{
"Banners": [
{
"banner_id": "30",
"banner_image": ""
}
],
"success": "success",
"message": "Banners"
}
on 2nd hit
{
"Banners": [
{
"banner_desc": "returns between paragraphs",
"banner_type": "regular",
"banner_size": 100,
}
],
"success": "success",
"message": "Banners"
}
on 3rd hit -
{
"user_id": "4",
"name": "",
"email": "k#gmail.com",
"mobile": "",
"image": "",
"success": "success",
"message": "Registered"
}

Dynamic response of Retrofit

My answer Json depends on whether it succeeds or not.
Unsuccessful example:
{
"success": false,
"errors": {
"email": "Could not find email address"
}
}
Successful example:
{
"success": true,
"user": {
"id": 6,
"fname": "XXXXXX",
"lname": "XXXXXX",
"email": "Username#mail.ca",
"roles": [
"Player"
"Coach"
"manager",
"Admin"
]
"date_registered": "2018-03-16T17: 49: 05.000Z"
}
"Token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzaWQiOiJiNjU1MDVkOGJiYzZhMTg1Y2E5MjU5NDlmNTU0OTc0MTgzM2Y2N2NiNjFjYThkMzNkMTUxY2U2MDhjMTBmNTllIiwiaWF0IjoxNTI3MjY3MzEwLCJleHAiOjE1Mjc4NzIxMTB9.p5pTlNjTsr-8N_8B3M5fW3T6PTTrcFo8D77N0WWgA3c"
}
Now, I want to have a POJO for both at the same time with retrofit.
Thank you
Edit : I just solved the problem by changing the form of JSON to :
{
"success": true,
"data": {
"user": {
"id": 6,
"fname": "XXXXXXX",
"lname": "XXXXXXXX",
"email": "Username#mail.ca",
"roles": [
"player",
"coach",
"manager",
"admin"
],
"activation_state": 0,
"date_registered": "2018-03-16T17:49:05.000Z"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzaWQiOiI0MTFlZmI5Y2ExYzY1ZWFlYzQ4Yzg1ZjJkYTQwOThmODBjOTk1NWNjNjcyOTNlODI5NmI4N2RjZWY5OTMzYzljIiwiaWF0IjoxNTI4NDI0MDA1LCJleHAiOjE1Mjg0MjQ2MDl9.lTsQ867Lk78RV2ruaQFyxUNfm58bHpfzEsZnvKJQMXQ"
},
"errors": {}
}
Thank you for help
You could simply return a String Retrofit, and then parse it manually.
If not, then you have to create a POJO object that contains all variables from both objects.
And then at runtime you check if "success" is true/false, and then try to access the underlying varaibles.
Copy your json response and past http://pojo.sodhanalibrary.com/
Then submit
You will get multiple pojo class with respect to your response ,

datatables Load data exception

I've got the JSON data behind the scenes, that's it
[{"aid":100000,"name":"JYCM201609010250","rtsp":"947|100000|3750","statuz":"1","updateTime":"2017-05-31"},{"aid":100001,"name":"gui","rtsp":"947|100000|3750","statuz":"0","updateTime":"2017-05-31"}]
Background and foreground code are as follows
#Autowired
private MediaImpl media;
#ResponseBody
#RequestMapping(value = "/media",method = RequestMethod.GET)
public List<Media> MediaAll(){
System.out.println("------------------------------------------------------");
return media.findAll();
}
JS code is as follows
<script>
$(document).ready(function () {
$('#table_id_example').DataTable({
"iDisplayLength": 10,
"bLengthChange": false,
"ajax": {
"url": "/media",
"dataType": "json",
"success": function (json) {
console.log(json)
}
},
"columns": [
{
"data": 'aid'
},
{
"data": 'name'
},
{
"data": 'rtsp'
},
{
"data": 'statuz'
},
{
"data": 'updateTime'
}
]
});
});
html code is as follows
The console code
VM178:10 (2) [{…}, {…}]0: {aid: 100000, name: "JYCM201609010250", rtsp: "947|100000|3750", statuz: "1", updateTime: "2017-05-31"}1: {aid: 100001, name: "gui", rtsp: "947|100000|3750", statuz: "0", updateTime: "2017-05-31"}length: 2__proto__: Array(0)
There is no error in the front-end console, and no errors in the back end.But the data is not available
There are a couple of problems here. The first is that datatables expects data in a data element of the json response, such as:
{
data: [{"aid":100000,"name":"JYCM201609010250","rtsp":"947|100000|3750","statuz":"1","updateTime":"2017-05-31"},{"aid":100001,"name":"gui","rtsp":"947|100000|3750","statuz":"0","updateTime":"2017-05-31"}]
}
You should be able to use ajaxSrc: "" on your DataTable settings.
The second problem is with your ajax settings. DataTables states you can not supply the success callback in the ajax settings as it uses this internally.
Documentation on both of these issues:
https://datatables.net/reference/option/ajax
Assuming you are using DataTables 1.10.x

How do I format JSON for Broadleaf Commerce REST API - Wrapper is members are null?

I created a new path on the Catalog Endpoint. It is suppose to accept a JSON representation of a Product and add it to the database.
public ProductWrapper insertProduct(HttpServletRequest request, ProductWrapper wrapper)
{
return wrapper;
}
#RequestMapping(value="product",method=RequestMethod.POST)
public ProductWrapper addProduct(HttpServletRequest request, ProductWrapper wrapper){
return insertProduct(request, wrapper);
}
But when I put the JSON in the body of the message. It is not saving it into my wrapper. My JSON looks like this :
{
"id": 1,
"name": "Sudden Death Sauce",
"longDescription": "As my Chilipals know, I am never one to be satisfied. Hence, the creation of Sudden Death. When you need to go beyond... Sudden Death will deliver! ",
"retailPrice": {
"amount": "10.99",
"currency": "USD"
},
"primaryMedia": {
"id": 101,
"title": "Sudden Death Sauce Bottle",
"url": "/cmsstatic/img/sauces/Sudden-Death-Sauce-Bottle.jpg",
"altText": "primary"
},
"active": true,
"activeStartDate": "2017-01-25T16:32:36.993-0500",
"manufacturer": "Blair's",
"defaultCategoryId": 2002,
"productAttribute": [
{
"id": 1,
"productId": 1,
"attributeName": "heatRange",
"attributeValue": "4"
}
],
"media": [
{
"id": 102,
"title": "Sudden Death Sauce Close-up",
"url": "/cmsstatic/img/sauces/Sudden-Death-Sauce-Close.jpg",
"altText": "alt1"
},
{
"id": 101,
"title": "Sudden Death Sauce Bottle",
"url": "/cmsstatic/img/sauces/Sudden-Death-Sauce-Bottle.jpg",
"altText": "primary"
}
]
}
Am I missing anything? I put a breakpoint and it hits it fine. The wrapper is instantiated but all the members are null.
You need to annotate the wrapper parameter with #RequestBody and also add an accepts on your #RequestMapping:
#RequestMapping(value="product",method=RequestMethod.POST, accepts="application/json")
public ProductWrapper addProduct(HttpServletRequest request, #RequestBody ProductWrapper wrapper){
return insertProduct(request, wrapper);
}
When you send your request, make sure you send a Content-Type header as well, like Content-Type=application/json so that Spring will serialize it appropriately.

Having trouble deserializing JSON response with gson

I am using an API where I supply an input string, and it returns some keyword autocompletions and product nodes.
My goal is to deserialize the response and get a list of the autocompletion Strings I can use. I'm trying implement this in an android application with the Retrofit library, which uses gson.
First off, I'm not sure the response I have is a typical JSON response. The 'nodes' item has key / value pairs, but the input string and the autocompletions list don't seem to have keys I can use.
["pol",
["polaroid camera",
"polo",
"polo ralph lauren",
"polo ralph lauren men",
"polar heart rate monitor",
"polaroid",
"polo shirt",
"polar watch",
"police scanner",
"polar"],
[{
"nodes": [{
"alias": "electronics",
"name": "Electronics"
},
{
"alias": "electronics-tradein",
"name": "Electronics Trade-In"
}]
},
{
},
{
},
{
},
{
},
{
},
{
},
{
},
{
},
{
}],
[]]
This is my attempt at the java classes for gson to deserialize to. However, it doesn't work as from what I understand, gson needs the class variables to match the JSON keys (true for Node class but not the rest).
class Response {
String input;
List<String> keywords;
List<Node> nodes;
}
class Node {
String alias;
String name;
}
the json only has a couple of keys in it, this is largely a Json Array.
if you can change the JSON, make it more like this
{
"input" : "pol",
"keywords" : ["polaroid camera","polo",...],
"nodes": [{
"alias": "electronics",
"name": "Electronics"
},
{
"alias": "electronics-tradein",
"name": "Electronics Trade-In"
}]
}

Categories