Here is the problem, when I send my object to server using retrofit I got it null. I'm doing this to create the json object:
HashMap<String, UserModel> map = new HashMap<>();
map.put("user", user);
But, when the json arrives in the server I got something like this:
{"user":null}
Then I printed ny json file with this line:
Log.d("TAG", new JSONObject(map).toString());
And I saw the same null object.
So, here is my question, Why is this happening? And how can I fix that?
Here goes some information about my project:
Retrofit version: 2.0.0
Retrofit serializer: jackson version 2.0.0
using also jackson to convert JodaTime version 2.4.0
here goes how I get retrofit instance:
public T buildServiceInstance(Class<T> clazz){
return new Retrofit.Builder().baseUrl(BuildConfig.API_HOST)
.addConverterFactory(JacksonConverterFactory.create())
.build().create(clazz);
}
I call that method here:
public static final IUserApi serviceInstance = new ApiBuildRequester<IUserApi>()
.buildServiceInstance(IUserApi.class);
Method declaration on interface IUserApi:
#POST("User.svc/Save")
Call<ResponseSaveUserApiModel> save(#Body HashMap<String, UserModel> map);
And at last, but I guess, not less important:
public class UserModel implements Parcelable {
private String idUser;
private String name;
private String email;
#JsonProperty("password")
private String safePassword;
private String salt;
private String phoneNumber;
private String facebookProfilePictureUrl;
private String facebookUserId;
public UserModel() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdUser() {
return idUser;
}
public void setIdUser(String idUser) {
this.idUser = idUser;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSafePassword() {
return safePassword;
}
public void setSafePassword(String safePassword) {
this.safePassword = safePassword;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getFacebookProfilePictureUrl() {
return facebookProfilePictureUrl;
}
public void setFacebookProfilePictureUrl(String facebookProfilePictureUrl) {
this.facebookProfilePictureUrl = facebookProfilePictureUrl;
}
public String getFacebookUserId() {
return facebookUserId;
}
public void setFacebookUserId(String facebookUserId) {
this.facebookUserId = facebookUserId;
}
#Override
public int describeContents() {
return 0;
}
public UserModel(Parcel in) { // Deve estar na mesma ordem do "writeToParcel"
setIdUser(in.readString());
setName(in.readString());
setEmail(in.readString());
setSafePassword(in.readString());
setPhoneNumber(in.readString());
setFacebookProfilePictureUrl(in.readString());
setFacebookUserId(in.readString());
}
#Override
public void writeToParcel(Parcel dest, int flags) { //Deve estar na mesma ordem do construtor que recebe parcel
dest.writeString(idUser);
dest.writeString(name);
dest.writeString(email);
dest.writeString(safePassword);
dest.writeString(phoneNumber);
dest.writeString(facebookProfilePictureUrl);
dest.writeString(facebookUserId);
}
public static final Parcelable.Creator<UserModel> CREATOR = new Parcelable.Creator<UserModel>(){
#Override
public UserModel createFromParcel(Parcel source) {
return new UserModel(source);
}
#Override
public UserModel[] newArray(int size) {
return new UserModel[size];
}
};
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}
Debug screen:
#Selvin and #cricket_007 You are the best!
I got this using your hint that my printing was wrong, and I found the solution.
I have two types of users in my app, facebook users or native users, two forms, but just one object, and here was the problem, when I sent facebook objects (complete) it worked fine, but when I tried to send native users, with some null properties, it crashed my serialization.
So I had to check every property before send it, it's just a workaround, but for now it's enough, thank you a lot folks!
This is the format of the JSON as configured in the API:
{
"Hotels":[
{
"EANHotelID":"257219",
"Country":"IN",
"Name":"Toshali Sands Ethnic Village Resort",
"LowRate":"88.32",
"HighRate":"118.77",
"Latitude":"19.83861",
"Longitude":"85.89400",
"Location":"Near the bay",
"PostalCode":"752002",
"PropertyCategory":"3",
"PropertyCurrency":"INR",
"StarRating":"4.0",
"StateProvince":"",
"CheckInTime":"10 AM",
"CheckOutTime":"8 AM",
"City":"Puri",
"Confidence":"52",
"AirportCode":"BBI",
"Caption":"Featured Image",
"ThumbnailURL":"http://media.expedia.com/hotels/2000000/1720000/1710100/1710078/1710078_35_t.jpg",
"URL":"http://media.expedia.com/hotels/2000000/1720000/1710100/1710078/1710078_35_b.jpg"
},
{
"EANHotelID":"397792",
"Country":"IN",
"Name":"MAYFAIR Heritage, Puri",
"LowRate":"138.8325",
"HighRate":"176.55",
"Latitude":"19.79851",
"Longitude":"85.83413",
"Location":"Near Puri Beach",
"PostalCode":"752002",
"PropertyCategory":"1",
"PropertyCurrency":"INR",
"StarRating":"4.0",
"StateProvince":"",
"CheckInTime":"8 AM",
"CheckOutTime":"8 AM",
"City":"Puri",
"Confidence":"60",
"AirportCode":"BBI",
"Caption":"Featured Image",
"ThumbnailURL":"http://media.expedia.com/hotels/5000000/4790000/4780200/4780106/4780106_20_t.jpg",
"URL":"http://media.expedia.com/hotels/5000000/4790000/4780200/4780106/4780106_20_b.jpg"
},
{
"EANHotelID":"397792",
"Country":"IN",
"Name":"MAYFAIR Heritage, Puri",
"LowRate":"138.8325",
"HighRate":"176.55",
"Latitude":"19.79851",
"Longitude":"85.83413",
"Location":"Near Puri Beach",
"PostalCode":"752002",
"PropertyCategory":"1",
"PropertyCurrency":"INR",
"StarRating":"4.0",
"StateProvince":"",
"CheckInTime":"8 AM",
"CheckOutTime":"8 AM",
"City":"Puri",
"Confidence":"60",
"AirportCode":"BBI",
"Caption":"Featured Image",
"ThumbnailURL":"http://media.expedia.com/hotels/5000000/4790000/4780200/4780106/4780106_20_t.jpg",
"URL":"http://media.expedia.com/hotels/5000000/4790000/4780200/4780106/4780106_20_b.jpg"
}
]
}
And these are the model classes I have used for parsing the json using GSON
hotel_list.java
public class hotel_list {
#SerializedName("Hotels")
#Expose
public ArrayList<hotel> hotel_list;
public ArrayList<hotel> getHotel_list() { return hotel_list;}
public void setHotel_list(ArrayList<hotel> hotel_list) {
this.hotel_list = hotel_list;
}
}
hotel.java
public class hotel {
#SerializedName("EANHotelID")
#Expose
private String EANHotelID;
#SerializedName("Country")
#Expose
private String Country;
#SerializedName("Name")
#Expose
private String Name;
#SerializedName("LowRate")
#Expose
private String LowRate;
#SerializedName("HighRate")
#Expose
private String HighRate;
#SerializedName("Latitude")
#Expose
private String Latitude;
#SerializedName("Longitude")
#Expose
private String Longitude;
#SerializedName("Location")
#Expose
private String Location;
#SerializedName("PostalCode")
#Expose
private String PostalCode;
#SerializedName("PropertyCategory")
#Expose
private String PropertyCategory;
#SerializedName("PropertyCurrency")
#Expose
private String PropertyCurrency;
#SerializedName("StarRating")
#Expose
private String StarRating;
#SerializedName("StateProvince")
#Expose
private String StateProvince;
#SerializedName("CheckInTime")
#Expose
private String CheckInTime;
#SerializedName("CheckOutTime")
#Expose
private String CheckOutTime;
#SerializedName("City")
#Expose
private String City;
#SerializedName("Confidence")
#Expose
private String Confidence;
#SerializedName("AirportCode")
#Expose
private String AirportCode;
#SerializedName("Caption")
#Expose
private String Caption;
#SerializedName("ThumbnailURL")
#Expose
private String ThumbnailURL;
#SerializedName("URL")
#Expose
private String URL;
public String getEANHotelID() {
return EANHotelID;
}
public void setEANHotelID(String EANHotelID) {
this.EANHotelID = EANHotelID;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLowRate() {
return LowRate;
}
public void setLowRate(String lowRate) {
LowRate = lowRate;
}
public String getHighRate() {
return HighRate;
}
public void setHighRate(String highRate) {
HighRate = highRate;
}
public String getLatitude() {
return Latitude;
}
public void setLatitude(String latitude) {
Latitude = latitude;
}
public String getLongitude() {
return Longitude;
}
public void setLongitude(String longitude) {
Longitude = longitude;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
public String getPostalCode() {
return PostalCode;
}
public void setPostalCode(String postalCode) {
PostalCode = postalCode;
}
public String getPropertyCategory() {
return PropertyCategory;
}
public void setPropertyCategory(String propertyCategory) {
PropertyCategory = propertyCategory;
}
public String getPropertyCurrency() {
return PropertyCurrency;
}
public void setPropertyCurrency(String propertyCurrency) {
PropertyCurrency = propertyCurrency;
}
public String getStarRating() {
return StarRating;
}
public void setStarRating(String starRating) {
StarRating = starRating;
}
public String getStateProvince() {
return StateProvince;
}
public void setStateProvince(String stateProvince) {
StateProvince = stateProvince;
}
public String getCheckInTime() {
return CheckInTime;
}
public void setCheckInTime(String checkInTime) {
CheckInTime = checkInTime;
}
public String getCheckOutTime() {
return CheckOutTime;
}
public void setCheckOutTime(String checkOutTime) {
CheckOutTime = checkOutTime;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getConfidence() {
return Confidence;
}
public void setConfidence(String confidence) {
Confidence = confidence;
}
public String getAirportCode() {
return AirportCode;
}
public void setAirportCode(String airportCode) {
AirportCode = airportCode;
}
public String getCaption() {
return Caption;
}
public void setCaption(String caption) {
Caption = caption;
}
public String getThumbnailURL() {
return ThumbnailURL;
}
public void setThumbnailURL(String thumbnailURL) {
ThumbnailURL = thumbnailURL;
}
public String getURL() {
return URL;
}
public void setURL(String URL) {
this.URL = URL;
}
}
And this is the AsyncTask doInBackground method which fetches the json and tries to parse it.
doInBackground
#Override
protected hotel_list doInBackground(Void... params) {
hotel_list hotelList = new hotel_list();
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpGet post = new HttpGet(url);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
Log.e(REST, Integer.toString(statusLine.getStatusCode()));
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
// Log.e(TAG, reader.readLine());
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
String str=reader.readLine();
Log.i("json object",str);
hotelList = gson.fromJson(reader, hotel_list.class);
content.close();
// handlePostsList(posts);
} catch (Exception ex) {
Log.e(REST, "Failed to parse JSON due to: " + ex);
}
} else {
Log.e(REST, "Server responded with status code: " + statusLine.getStatusCode());
}
} catch (Exception ex) {
Log.e(REST, "Failed to send HTTP POST request due to: " + ex);
}
Log.i("list",hotelList.getHotel_list().get(1).getName());
return hotelList;
}
Now the problem is that the hotelList being returned is null. GSON is not showing any errors but the parsed contents are not getting filled in the list and it remains empty. What am I doing wrong?
Logcat message -
09-23 01:42:52.374 1950-1963/com.neelraj.hotels W/art﹕ Suspending all threads took: 25.899ms
09-23 01:42:54.321 1950-1995/com.neelraj.hotels I/json object﹕ " {\"Hotels\":[{\"EANHotelID\":\"176933\",\"Country\":\"IN\",\"Name\":\"The Park Kolkata\",\"LowRate\":\"76.13\",\"HighRate\":\"226.5\",\"Latitude\":\"22.55409\",\"Longitude\":\"88.35143\",\"Location\":\"Near New Market\",\"PostalCode\":\"700016\",\"PropertyCategory\":\"1\",\"PropertyCurrency\":\"INR\",\"StarRating\":\"5.0\",\"StateProvince\":\"\",\"CheckInTime\":\"2 PM\",\"CheckOutTime\":\"noon\",\"City\":\"Kolkata\",\"Confidence\":\"52\",\"AirportCode\":\"CCU\",\"Caption\":\"Featured Image\",\"ThumbnailURL\":\"http://media.expedia.com/hotels/1000000/530000/523000/522928/522928_33_t.jpg\",\"URL\":\"http://media.expedia.com/hotels/1000000/530000/523000/522928/522928_33_b.jpg\"},{\"EANHotelID\":\"185519\",\"Country\":\"IN\",\"Name\":\"The Peerless Inn - Kolkata\",\"LowRate\":\"91.36\",\"HighRate\":\"137.04\",\"Latitude\":\"22.56217\",\"Longitude\":\"88.35157\",\"Location\":\"Near New Market\",\"PostalCode\":\"700 013\",\"PropertyCategory\":\"1\",\"PropertyCurrency\":\"INR\",\"StarRating\":\"4.0\",\"StateProvince\":\"\",\"CheckInTime\":\"noon\",\"CheckOutTime\":\"noon\",\"City\":\"Kolkata\",\"Confidence\":\"52\",\"AirportCode\":\"CCU\",\"Caption\":\"Featured Image\",\"ThumbnailURL\":\"http://media.expedia.com/hotels/2000000/1070000/1066400/1066383/1066383_13_t.jpg\",\"URL\":\"http://media.expedia.com/hotels/2000000/1070000/1066400/1066383/1066383_13_b.jpg\"},{\"EANHotelID\":\"516167\",\"Country\":\"IN\",\"Name\":\"Hotel O2 VIP\",\"LowRate\":\"56.32\",\"HighRate\":\"71.55\",\"Latitude\":\"22.63360\",\"Longitude\":\"88.43468\",\"Location\":\"In Kolkata (Dum Dum)\",\"PostalCode\":\"700052\",\"PropertyCategory\":\"1\",\"PropertyCurrency\":\"INR\",\"StarRating\":\"3.0\",\"StateProvince\":\"\",\"CheckInTime\":\"\",\"CheckOutTime\":\"noon\",\"City\":\"kolkata\",\"Confidence\":\"\",\"AirportCode\":\"CCU\",\"Caption\":\"Featured Image\",\"ThumbnailURL\":\"http://media.expedia.com/hotels/12000000/11040000/11032100/11032008/11032008_3_t.jpg\",\"URL\":\"http://media.expedia.com/hotels/12000000/11040000/11032100/11032008/11032008_3_b.jpg\"},{\"EANHotelID\":\"198401\",\"Country\":\"IN\",\"Name\":\"Taj Bengal\",\"LowRate\":\"192.7119\",\"HighRate\":\"859.6464\",\"Latitude\":\"22.53706\",\"Longitude\":\"88.33366\",\"Location\":\"Near Alipore Zoo\",\"PostalCode\":\"700 027\",\"PropertyCategory\":\"1\",\"PropertyCurrency\":\"INR\",\"StarRating\":\"5.0\",\"StateProvince\":\"\",\"CheckInTime\":\"2 PM\",\"CheckOutTime\":\"Noon\",\"City\":\"Kolkata\",\"Confidence\":\"95\",\"AirportCode\":\"CCU\",\"Caption\":\"Featured Image\",\"ThumbnailURL\":\"http://media.expedia.com/hotels/1000000/470000/465100/465007/465007_77_t.jpg\",\"URL\":\"http://media.expedia.com/hotels/1000000/470000/465100/465007/465007_77_b.jpg\"},{\"EANHotelID\":\"215054\",\"Country\":\"IN\",\"Name\":\"ITC Sonar Kolkata\",\"LowRate\":\"174.9995\",\"HighRate\":\"221.9965\",\"Latitude\":\"22.54331\",\"Longitude\":\"88.39665\",\"Location\":\"Near Science City\",\"PostalCode\":\"700046\",\"PropertyCategory\":\"1\",\"PropertyCurrency\":\"INR\",\"StarRating\":\"5.0\",\"StateProvince\":\"\",\"CheckInTime\":\"2 PM\",\"CheckOutTime\":\"\",\"City\":\"Kolkata\",\"Confidence\":\"52\",\"AirportCode\":\"CCU\",\"Caption\":\"Featured Image\",\"ThumbnailURL\":\"http://media.expedia.com/hotels/1000000/930000/922100/922011/922011_66_t.jpg\",\"URL\":\"http://media.expedia.com/hotels/1000000/930000/922100/922011/922011_66_b.jpg\"},{\"EANHotelID\":\"219474\",\"Country\":\"IN\",\"Name\":\"Golden Parkk\",\"LowRate\":\"78.57\",\"HighRate\":\"126.9\",\"Latitude\":\"22.54741\",\"Longitude\":\"88.34966\",\"Location\":\"Near Victoria Memorial\",\"PostalCode\":\"700071\",\"PropertyCategory\":\"1\",\"PropertyCurrency\":\"INR\",\"StarRating\":\"3.0\",\"StateProvince\":\"\",\"CheckInTime\":\"3 PM\",\"CheckOutTime\":\"noon\",\"City\":\"Kolkata\",\"Confidence\":\"52\",\"AirportCode\":\"CCU\",\"Caption\":\"Featured Image\",\"ThumbnailURL\":\"http://media.expedia.com/hotels/2000000/1060000/1056000/1055970/1055970_41_t.jpg\",\"URL\":\"http://media.expedia.com/hotels/2000000/1060000/105
09-23 01:42:54.344 1950-1995/com.neelraj.hotels E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.neelraj.hotels, PID: 1950
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList com.neelraj.hotels.model.hotel_list.getHotel_list()' on a null object reference
at com.neelraj.hotels.MainActivity$Fetch.doInBackground(MainActivity.java:153)
at com.neelraj.hotels.MainActivity$Fetch.doInBackground(MainActivity.java:84)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
Try to change generic list type to simple array:
public ArrayList<hotel> hotel_list;
to:
public hotel[] hotel_list;
and
Gson gson = gsonBuilder.create();
to:
Gson gson = new Gson();
problem could be this:
hotelList = gson.fromJson(reader, hotel_list.class);
change to:
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = reader.readLine()) != null) {
builder.append(aux);
}
hotelList = gson.fromJson(builder.toString(), hotel_list.class);
You are read your data out of your input stream into a string, and then passing that input stream to your JSON parsing routine. It is already at the end of the file, so it reads an empty input which is not objects/arrays and returns null. You should either remove the following lines--
String str=reader.readLine();
Log.i("json object",str);
OR pass in the string you already read --
hotelList = gson.fromJson(str, hotel_list.class); //pass str instead of reader
I would recommend not pre-reading into a string because it is going to be more efficient and handle multiple line files.
My suggestion to you is to use the following:
http://www.jsonschema2pojo.org
Find what you need and then try it out in your app.
Also the name of the class should be capital.
EDIT
If using List doesn't work try as in the following example:
http://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON
Here they do using the arrays([]).
I need to parse a JSON response that I receive from a web service but I am receiving following error message, I puzzled with the this. I tried it without Results class as well to no avail. Any help would be appreciated.
The request sent by the client was syntactically incorrect.
Code
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new
MappingJackson2HttpMessageConverter());
ResponseEntity<Results> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi
/GetEvents?
username=username&
password=password&
userid=23",
Results.class);
System.err.println(">>" + responseEntity.getBody().getEvents().size());
Classes
Results
public class Results {
private List<Events> events;
getter and setter
}
Events
public class Event {
private long eventId;
private String name;
private String subTitle;
private String description;
private String localDate;
private String localDateFrom;
private String imageUrl;
private int venueId;
private String venue;
private int availableTickets;
private long performerId;
private String performer;
private String performerType;
private int subcategoryId;
private String urlCategoryName;
private String metaTitle;
private String metaDescription;
private String primeSportUrl;
private String sectionWiseView;
private String venueCity;
private String venueState;
private String snippetDate;
private int eiProductionId;
private boolean requireBillingAsShipping;
public long getEventId() {
return eventId;
}
public void setEventId(long eventId) {
this.eventId = eventId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLocalDate() {
return localDate;
}
public void setLocalDate(String localDate) {
this.localDate = localDate;
}
public String getLocalDateFrom() {
return localDateFrom;
}
public void setLocalDateFrom(String localDateFrom) {
this.localDateFrom = localDateFrom;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public int getVenueId() {
return venueId;
}
public void setVenueId(int venueId) {
this.venueId = venueId;
}
public String getVenue() {
return venue;
}
public void setVenue(String venue) {
this.venue = venue;
}
public int getAvailableTickets() {
return availableTickets;
}
public void setAvailableTickets(int availableTickets) {
this.availableTickets = availableTickets;
}
public long getPerformerId() {
return performerId;
}
public void setPerformerId(long performerId) {
this.performerId = performerId;
}
public String getPerformer() {
return performer;
}
public void setPerformer(String performer) {
this.performer = performer;
}
public String getPerformerType() {
return performerType;
}
public void setPerformerType(String performerType) {
this.performerType = performerType;
}
public int getSubcategoryId() {
return subcategoryId;
}
public void setSubcategoryId(int subcategoryId) {
this.subcategoryId = subcategoryId;
}
public String getUrlCategoryName() {
return urlCategoryName;
}
public void setUrlCategoryName(String urlCategoryName) {
this.urlCategoryName = urlCategoryName;
}
public String getMetaTitle() {
return metaTitle;
}
public void setMetaTitle(String metaTitle) {
this.metaTitle = metaTitle;
}
public String getMetaDescription() {
return metaDescription;
}
public void setMetaDescription(String metaDescription) {
this.metaDescription = metaDescription;
}
public String getPrimeSportUrl() {
return primeSportUrl;
}
public void setPrimeSportUrl(String primeSportUrl) {
this.primeSportUrl = primeSportUrl;
}
public String getSectionWiseView() {
return sectionWiseView;
}
public void setSectionWiseView(String sectionWiseView) {
this.sectionWiseView = sectionWiseView;
}
public String getVenueCity() {
return venueCity;
}
public void setVenueCity(String venueCity) {
this.venueCity = venueCity;
}
public String getVenueState() {
return venueState;
}
public void setVenueState(String venueState) {
this.venueState = venueState;
}
public String getSnippetDate() {
return snippetDate;
}
public void setSnippetDate(String snippetDate) {
this.snippetDate = snippetDate;
}
public int getEiProductionId() {
return eiProductionId;
}
public void setEiProductionId(int eiProductionId) {
this.eiProductionId = eiProductionId;
}
public boolean isRequireBillingAsShipping() {
return requireBillingAsShipping;
}
public void setRequireBillingAsShipping(boolean requireBillingAsShipping) {
this.requireBillingAsShipping = requireBillingAsShipping;
}
}
Partial Response
[{
"EventId":1000250537,
"Name":"US Open Golf",
"SubTitle":null,
"Description":"US Open Golf Tickets",
"Date":"\/Date(1434873560000)\/",
"LocalDate":"6/20/2015 11:59 PM",
"LocalDateFrom":null,
"ImageUrl":null,
"VenueId":146566,
"Venue":"Chambers Bay Golf Course",
"AvailableTickets":33,
"PerformerId":151551,
"Performer":"US Open Golf",
"PerformerType":"Golf",
"SubcategoryId":55,
"UrlCategoryName":"Sports",
"MetaTitle":null,
"MetaDescription":null,
"PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",
"SectionWiseView":null,
"VenueCity":"UNIVERSITY PLACE",
"VenueState":"WA",
"SnippetDate":null,
"EIProductionId":99985,
"RequireBillingAsShipping":false},
{
"EventId":1000253479,
"Name":"Womens College World Series",
"SubTitle":null,
"Description": .....
UPDATE
I know JAXB can be used for both JSON and XML, I am trying to use it to see if it would help to solve the issue.
UPDATE
The code is returning following exception:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token
at [Source: java.io.PushbackInputStream#dedcd10; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token
at [Source: java.io.PushbackInputStream#dedcd10; line: 1, column: 1]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:208)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:200)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:97)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:809)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:793)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:576)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:529)
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:261)
at com.myproject.service.TicketSeviceImpl.primeSport(TicketSeviceImpl.java:217)
at com.myproject.service.TicketSeviceImpl.findTicket(TicketSeviceImpl.java:45)
at com.myproject.web.TicketController.findTicket(TicketController.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
UPDATE
following code returns
Code
try {
System.err.println(">>> primeSport");
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(
new MappingJackson2HttpMessageConverter());
ResponseEntity<Event[]> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi/GetEvents?username=username&password=password&userid=23",
Event[].class);
System.err.println(">>" + responseEntity.getBody().length);
System.err.println(">>" + responseEntity.getBody()[0].getEventId());
System.err.println(">>" + responseEntity.getBody()[1].getEventId());
} catch (Exception e) {
e.printStackTrace();
}
Output
>1532
>0
>0
Can you try the following and see whether helps:
ResponseEntity<Events[]> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi
/GetEvents?
username=username&
password=password&
userid=23",
Events[].class);
System.err.println(">>" + responseEntity.getBody().length);
For mapping the fields to the JSON members you can use Jackson annotation JSONProperty("EventId") can be used for the eventId field. Similarly for others.
#JsonProperty("EventId")
private long eventId;
#JsonProperty("Name")
private String name;
Have you tried to see the exact request getting generated? Let's say in a proxy software like fiddler/charles?
Sometimes I have experienced, the framework adds additional constructs(encoding, etc), before the requests actually really gets to the wire(or reaching the server endpoint).
Try this, to create the request. Even the documentation for RestTemplate suggests to avoid double encoding for URL. It may not be very apparent when looking in the IDE.
String url = "http://primesport.sieenasoftware.com/QryApi/GetEvents?";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("username", "username");
params.add("password", "password");
params.add("userid", "23");
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build();
System.out.println(uriComponents.toUri());
Please let me know, how it works out.
Also, please let know, if you cant find steps to setup fiddler proxy. It quite a handy tool, while coding the service clients.
According to the json format, all you need is using the Event class instead of the Result class.
Or change the JSON result to this :
["events": {
"EventId":1000250537,
"Name":"US Open Golf",
"SubTitle":null,
"Description":"US Open Golf Tickets",
"Date":"\/Date(1434873560000)\/",
"LocalDate":"6/20/2015 11:59 PM",
"LocalDateFrom":null,
"ImageUrl":null,
"VenueId":146566,
"Venue":"Chambers Bay Golf Course",
"AvailableTickets":33,
"PerformerId":151551,
"Performer":"US Open Golf",
"PerformerType":"Golf",
"SubcategoryId":55,
"UrlCategoryName":"Sports",
"MetaTitle":null,
"MetaDescription":null,
"PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",
"SectionWiseView":null,
"VenueCity":"UNIVERSITY PLACE",
"VenueState":"WA",
"SnippetDate":null,
"EIProductionId":99985,
"RequireBillingAsShipping":false},
{
"EventId":1000253479,
"Name":"Womens College World Series",
"SubTitle":null,
"Description": .....
You can try importing Jackson Jar or add dependency in pom.xml if you are using Maven.
ObjectMapper mapper = new ObjectMapper();
try
{
mapper.writeValue(new File("c://temp/employee.json"), Results);
}
I have tried several ways to create follwing format json using java. (Gson , Jackson , ...)
{
"outbound": {
"address": [
"t91",
"t0992"
],
"send": "t678",
"outMessage": {
"message": "Hello World"
},
"client": "156",
"receipt": {
"URL": "http://example.com/Delivery",
"callback": "some-to-the-request"
},
"senderName": "Inc."
}
}
Any help?
Use code below.
Create POJO
public class TestPojo {
private Outbound outbound;
public Outbound getOutbound() {
return outbound;
}
public void setOutbound(Outbound outbound) {
this.outbound = outbound;
}
}
class Outbound {
private String[] address;
private String send;
private OutMessage outMessage;
private Receipt receipt;
private String senderName;
public String[] getAddress() {
return address;
}
public void setAddress(String[] address) {
this.address = address;
}
public String getSend() {
return send;
}
public void setSend(String send) {
this.send = send;
}
public OutMessage getOutMessage() {
return outMessage;
}
public void setOutMessage(OutMessage outMessage) {
this.outMessage = outMessage;
}
public Receipt getReceipt() {
return receipt;
}
public void setReceipt(Receipt receipt) {
this.receipt = receipt;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
}
class OutMessage {
private String message;
public OutMessage(String message) {
super();
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
class Receipt {
private String URL;
private String callback;
public Receipt(String uRL, String callback) {
super();
URL = uRL;
this.callback = callback;
}
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
public String getCallback() {
return callback;
}
public void setCallback(String callback) {
this.callback = callback;
}
}
Main Class (JSON to Object)
String json = "{'outbound':{'address':['t91','t0992'],'send':'t678','outMessage':{'message':'Hello World'},'receipt':{'URL':'http://example.com/Delivery','callback':'some-to-the-request'},'senderName':'Inc.'}}";
TestPojo testPojo = new Gson().fromJson(json, TestPojo.class);
System.out.println(testPojo.getOutbound().getSenderName());
Output
Inc.
Main Class (Object to JSON)
TestPojo testPojo = new TestPojo();
Outbound outbound = new Outbound();
outbound.setAddress(new String[]{"t91", "t0992"});
outbound.setOutMessage(new OutMessage("Hello World"));
outbound.setReceipt(new Receipt("http://example.com/Delivery", "some-to-the-request"));
outbound.setSenderName("Inc.");
outbound.setSend("t678");
testPojo.setOutbound(outbound);
System.out.println(new Gson().toJson(testPojo));
Output
{"outbound":{"address":["t91","t0992"],"send":"t678","outMessage":{"message":"Hello World"},"receipt":{"URL":"http://example.com/Delivery","callback":"some-to-the-request"},"senderName":"Inc."}}
Detail
Used GSON library.
Used a json given by you.
An example JSON object is shown below:
[{"Title":"John Doe","Address":{"AddressLines":["The Place","123 New Place","London","England"],"Postcode":"NW7 XXY"},"Telephone":"0012345","Email":"","Latitude":51.5024472101345,"Longitude":-0.557585646554,"Easting":500623,"Northing":179647}]
Suppose the above object is accessed via the link www.domain.com and I have the following class to represent the data
public class LocationData extends Data{
private Address Address;
private String Telephone;
private String Email;
private String Latitude;
private String Longitude;
private String Easting;
private String Northing;
public Address getAddress() {
return Address;
}
public void setAddress(Address address) {
Address = address;
}
public String getTelephone() {
return Telephone;
}
public void setTelephone(String telephone) {
Telephone = telephone;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getLatitude() {
return Latitude;
}
public void setLatitude(String latitude) {
Latitude = latitude;
}
public String getLongitude() {
return Longitude;
}
public void setLongitude(String longitude) {
Longitude = longitude;
}
public String getEasting() {
return Easting;
}
public void setEasting(String easting) {
Easting = easting;
}
public String getNorthing() {
return Northing;
}
public void setNorthing(String northing) {
Northing = northing;
}
}
And the address class is as follows:
public class Address {
public String[] AddressLines;
public String Postcode;
public String getPostcode() {
return Postcode;
}
public void setPostcode(String postcode) {
Postcode = postcode;
}
public String[] getAddressLines() {
return AddressLines;
}
public void setAddressLines(String addressLines[]) {
AddressLines = addressLines;
}
}
When I try to run
LocationData[] data = gson.fromJson(this.locationServiceUrl, LocationData[].class);
return data;
I get the following error:
Expected BEGIN_ARRAY but was string at the above mentioned line of code. I am not sure if there is something wrong in the manner in which I have set up my classes. Note: I am using an array (LocationData[] data) because the service returns multiple locations although I have just included one in the example shown above. Any help as to why this is happening is much appreciated. I have looked at some of the similar errors on here but none of the fixes provided seem to work for me.
{
"finally":[
{
"Title":"John Doe",
"Address": {
"AddressLines":[
"The Place",
"123 New Place",
"London",
"England"
],
"Postcode":"NW7XXY"
},
"Telephone":"0012345",
"Email":"",
"Latitude":51.5024472101345,
"Longitude":-0.557585646554,
"Easting":500623,
"Northing":179647
}
]
}
and code to parse this JSON is :
public class mainData {
public List<LocationData> finally;
public String[] getLocationData() {
return AddressLines;
}
public void setLocationData(List<LocationData> finally) {
this.finally = finally;
}
}
it is because your string starting with [ when you parsing this type of Json with Gson then you need to prefix a label to it just i like did ( {"finally": your data }).
Actually Gson trying to map the label and its value but in your case your [ doesnt contain Label by which Gson can map.