Gson parsing problems, null pointer exception - java
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([]).
Related
When retrieving json array from empty sharedpreference, java.lang.String cannot be converted to JSONObject exception comes
W/System.err: org.json.JSONException: Value Responsemodel$Banner#b494bac at 0 of type java.lang.String cannot be converted to JSONObject output: [Responsemodel$Banner#e5af3c3, Responsemodel$Banner#ed16440, Responsemodel$Banner#5335f79, Responsemodel$Banner#e8cb4be, Responsemodel$Banner#9ef091f] Getting from SharedPreferences String getbanner = preferences.getString(Constants.banner_list, null); Log.i("banner_str", getbanner); if (getbanner != null) { JSONArray jsonArray2 = new JSONArray(getbanner); Log.i("Sharedpref1", jsonArray2.toString()); if (banner_list != null) { banner_list.clear(); Log.i("Sharedpref2", jsonArray2.toString()); for (int x = 0; x < jsonArray2.length(); x++) { String object = jsonArray2.getJSONObject(x).getString("imgUrl"); Log.i("bid", object); HashMap<String, String> map = new HashMap<>(); map.put("imgUrl", object); banner_list.add(map); } } } } catch (NullPointerException | JSONException e1) { e1.printStackTrace(); } Banner_adapter adapter1 = new Banner_adapter(banner_list); snapHelper.attachToRecyclerView(recyclerView); recyclerView.setAdapter(adapter1); adapter1.notifyDataSetChanged(); Saved in SharedPreferences getbalres_dto model = response.body(); SharedPreferences.Editor editor = preferences.edit(); editor.putString(Constants.currentBalance, model.getMOBILEAPPLICATION().getCurrentBalance()) .putString(Constants.outletName, model.getMOBILEAPPLICATION().getOutletName()) .putString(Constants.name, model.getMOBILEAPPLICATION().getName()) .putString(Constants.news, model.getMOBILEAPPLICATION().getNews()) .putString(Constants.banner_list, model.getMOBILEAPPLICATION().getBanner().toString()) .putString(Constants.instaurl, model.getMOBILEAPPLICATION().getInstagramUrl()) .putString(Constants.fburl, model.getMOBILEAPPLICATION().getFacebookUrl()) .putString(Constants.youtubeurl, model.getMOBILEAPPLICATION().getYoutubeUrl()) .putString(Constants.twitterurl, model.getMOBILEAPPLICATION().getTwitterUrl()) .putString(Constants.aepsBalance, model.getMOBILEAPPLICATION().getAepsBalance()) .putString(Constants.cartItem, model.getMOBILEAPPLICATION().getCartItem()) .commit(); Java PoJO class public class getbalres_dto { #SerializedName("MOBILE_APPLICATION") #Expose private MOBILEAPPLICATION mOBILEAPPLICATION; public MOBILEAPPLICATION getMOBILEAPPLICATION() { return mOBILEAPPLICATION; } public void setMOBILEAPPLICATION(MOBILEAPPLICATION mOBILEAPPLICATION) { this.mOBILEAPPLICATION = mOBILEAPPLICATION; } public class MOBILEAPPLICATION { #SerializedName("response") #Expose private String response; #SerializedName("Message") #Expose private String message; #SerializedName("news") #Expose private String news; #SerializedName("banner") #Expose private JsonArray banner; #SerializedName("name") #Expose private String name; #SerializedName("outletName") #Expose private String outletName; #SerializedName("currentBalance") #Expose private String currentBalance; #SerializedName("aepsBalance") #Expose private String aepsBalance; #SerializedName("activationAmount") #Expose private String activationAmount; #SerializedName("transactionAmount") #Expose private String transactionAmount; #SerializedName("totalAmount") #Expose private String totalAmount; #SerializedName("isPaid") #Expose private String isPaid; #SerializedName("rentalType") #Expose private String rentalType; #SerializedName("instagramUrl") #Expose private String instagramUrl; #SerializedName("twitterUrl") #Expose private String twitterUrl; #SerializedName("facebookUrl") #Expose private String facebookUrl; #SerializedName("youtubeUrl") #Expose private String youtubeUrl; #SerializedName("cartItem") #Expose private String cartItem; public String getAepsBalance() { return aepsBalance; } public void setAepsBalance(String aepsBalance) { this.aepsBalance = aepsBalance; } public String getInstagramUrl() { return instagramUrl; } public void setInstagramUrl(String instagramUrl) { this.instagramUrl = instagramUrl; } public String getTwitterUrl() { return twitterUrl; } public void setTwitterUrl(String twitterUrl) { this.twitterUrl = twitterUrl; } public String getFacebookUrl() { return facebookUrl; } public void setFacebookUrl(String facebookUrl) { this.facebookUrl = facebookUrl; } public String getYoutubeUrl() { return youtubeUrl; } public void setYoutubeUrl(String youtubeUrl) { this.youtubeUrl = youtubeUrl; } public String getRentalType() { return rentalType; } public void setRentalType(String rentalType) { this.rentalType = rentalType; } public String getIsPaid() { return isPaid; } public void setIsPaid(String isPaid) { this.isPaid = isPaid; } public String getTotalAmount() { return totalAmount; } public void setTotalAmount(String totalAmount) { this.totalAmount = totalAmount; } public String getTransactionAmount() { return transactionAmount; } public void setTransactionAmount(String transactionAmount) { this.transactionAmount = transactionAmount; } public String getActivationAmount() { return activationAmount; } public void setActivationAmount(String activationAmount) { this.activationAmount = activationAmount; } public String getResponse() { return response; } public void setResponse(String response) { this.response = response; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getNews() { return news; } public void setNews(String news) { this.news = news; } public JsonArray getBanner() { return banner; } public void setBanner(JsonArray banner) { this.banner = banner; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOutletName() { return outletName; } public void setOutletName(String outletName) { this.outletName = outletName; } public String getCartItem() { return cartItem; } public void setCartItem(String cartItem) { this.cartItem = cartItem; } public String getCurrentBalance() { return currentBalance; } public void setCurrentBalance(String currentBalance) { this.currentBalance = currentBalance; } }}
Getting From SharedPreference String getbanner = preferences.getString(Constants.banner_list, null); Gson gson = new Gson(); Log.i("bannerdata__", getbanner); try { if (getbanner.isEmpty() || getbanner==null || getbanner.equalsIgnoreCase(null)) { Log.i("bannerdata__", "empty......"); } else { Type type = new TypeToken<List<String>>() { }.getType(); List<String> data = gson.fromJson(getbanner, type); for (String imgstr : data) { Log.i("bannerdata_2", imgstr); HashMap<String, String> map = new HashMap<>(); map.put("imgUrl", imgstr); banner_list.add(map); } Banner_adapter adapter1 = new Banner_adapter(banner_list); snapHelper.attachToRecyclerView(recyclerView); recyclerView.setAdapter(adapter1); adapter1.notifyDataSetChanged(); } } catch (Exception e) { e.printStackTrace(); } Add data in SharedPreference final ArrayList<String> arrPackage = new ArrayList<>(); try { JSONArray jsonArray2 = new JSONArray(getbalmodel.getMOBILEAPPLICATION().getBanner().toString()); if (banner_list != null) { banner_list.clear(); } for (int x = 0; x < jsonArray2.length(); x++) { String bid = jsonArray2.getJSONObject(x).getString("imgUrl"); arrPackage.add(bid); Gson gson = new Gson(); String json = gson.toJson(arrPackage); editor.putString(Constants.banner_list, json); Log.i("imageurl", bid); HashMap<String, String> map = new HashMap<>(); map.put("imgUrl", bid); banner_list.add(map); } editor.commit(); } catch (JSONException | NullPointerException e1) { e1.printStackTrace(); }
Retrofit + Observable - Expected BEGIN_ARRAY but was BEGIN_OBJECT
I'm trying to use New York Times API with Retrofit using Observable. But I'm getting this error when trying to use datas. Can someone help me see where I'm wrong, please ? Here is my ApiServices interface: #GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage") Observable<TopStoryResult> getTopStories(); #GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage") Observable<List<NewsItem>> getResults(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.nytimes.com/") .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create())) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); Here is my ApiStreams class public static Observable<TopStoryResult> streamFetchTopStories(){ ApiServices mApiServices = ApiServices.retrofit.create(ApiServices.class); return mApiServices.getTopStories() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .timeout(10, TimeUnit.SECONDS); } public static Observable<List<NewsItem>> streamFetchNews(){ ApiServices mApiServices = ApiServices.retrofit.create(ApiServices.class); return mApiServices.getResults() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .timeout(10, TimeUnit.SECONDS); } And this is what I'm trying to do in my MainActivity. For now I just want to display in a TextView the list of each Title... //------------------------ // Update UI //------------------------ private void updateUIWhenStartingHttpRequest() { this.textView.setText("Downloading..."); } private void updateUIWhenStopingHttpRequest(String response) { this.textView.setText(response); } //------------------------ // Rx Java //------------------------ private void executeRequestWithRetrofit(){ this.updateUIWhenStartingHttpRequest(); this.disposable = ApiStreams.streamFetchNews() .subscribeWith(new DisposableObserver<List<NewsItem>>(){ #Override public void onNext(List<NewsItem> topStories) { Log.e("TAG", "On Next"); updateUIWithResult(topStories); } #Override public void onError(Throwable e) { Log.e("ERROR", Log.getStackTraceString(e)); } #Override public void onComplete() { Log.e("TAG", "On Complete !"); } }); } private void updateUIWithResult(List<NewsItem> newsItemList){ StringBuilder mStringBuilder = new StringBuilder(); for (NewsItem news : newsItemList){ Log.e("TAG", "UPDATE UI" + news.getTitle()); mStringBuilder.append("- " + news.getTitle() + "\n"); } updateUIWhenStopingHttpRequest(mStringBuilder.toString()); } [EDIT] There are my two models for TopStories and NewsItem TopStories: private String status; private String copyright; private String section; private String lastUpdated; private Integer numResults; private List<NewsItem> results = null; public String getStatus() {return status; } public void setStatus(String status) { this.status = status; } public String getCopyright() { return copyright; } public void setCopyright(String copyright) { this.copyright = copyright; } public String getSection() { return section; } public void setSection(String section) { this.section = section; } public String getLastUpdated() { return lastUpdated; } public void setLastUpdated(String lastUpdated) { this.lastUpdated = lastUpdated; } public Integer getNumResults() { return numResults; } public void setNumResults(Integer numResults) { this.numResults = numResults; } public List<NewsItem> getResults() { return results; } public void setResults(List<NewsItem> results) { this.results = results; } NewsItem: private String section; private String subsection; private String title; private String url; private String byline; private String updated_date; private String created_date; private String published_date; private String material_type_facet; private String kicker; #SerializedName("abstract") private String abstract_string; private List<Multimedia> multimedia; private transient String des_facet; private transient String org_facet; private transient String per_facet; private transient String geo_facet; public NewsItem() { } public NewsItem(String url) { this.url = url; } public NewsItem(String section, String subsection, String title, String url, String byline, String updated_date, String created_date, String published_date, String material_type_facet, String kicker) { this.section = section; this.subsection = subsection; this.title = title; this.url = url; this.byline = byline; this.updated_date = updated_date; this.created_date = created_date; this.published_date = published_date; this.material_type_facet = material_type_facet; this.kicker = kicker; } public String getSection() { return section; } public void setSection(String section) { this.section = section; } public String getSubsection() { return subsection; } public void setSubsection(String subsection) { this.subsection = subsection; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getByline() { return byline; } public void setByline(String byline) { this.byline = byline; } public String getUpdated_date() { return updated_date; } public void setUpdated_date(String updated_date) { this.updated_date = updated_date; } public String getCreated_date() { return created_date; } public void setCreated_date(String created_date) { this.created_date = created_date; } public String getPublished_date() { return published_date; } public void setPublished_date(String published_date) { this.published_date = published_date; } public String getMaterial_type_facet() { return material_type_facet; } public void setMaterial_type_facet(String material_type_facet) { this.material_type_facet = material_type_facet; } public String getKicker() { return kicker; } public void setKicker(String kicker) { this.kicker = kicker; } public String getAbstract() { return abstract_string; } public void setAbstract(String abstract_string) { this.abstract_string = abstract_string; } public List<Multimedia> getMultimedia() { return multimedia; } public void setMultimedia(List<Multimedia> multimedia) { this.multimedia = multimedia; } public String getDes_facet() { return des_facet; } public void setDes_facet(String des_facet) { this.des_facet = des_facet; } public String getOrg_facet() { return org_facet; } public void setOrg_facet(String org_facet) { this.org_facet = org_facet; } public String getPer_facet() { return per_facet; } public void setPer_facet(String per_facet) { this.per_facet = per_facet; } public String getGeo_facet() { return geo_facet; } public void setGeo_facet(String geo_facet) { this.geo_facet = geo_facet; } Here is what the JSON looks like: JSON First when I tried this one with Github user API, it works fine. But I can't figure out where I'm wrong there... Is anybody can help me please ? Thanks a lot !
Expected BEGIN_ARRAY but was BEGIN_OBJECT this means you are trying to a get a JSON Array as a List in JAVA but the api sent you a JSON OBJECT. So I cannot gather enough information but if I have to guess you should change this #GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage") Observable<List<NewsItem>> getResults(); to #GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage") Observable<NewsItemObject> getResults(); NewsItemObject is the Class that wraps NewsItem
In your ApiServices interface you expect that getResults() returns Observable<List<NewsItem>>. Based on JSON you getting back this is not gonna work, because your root JSON element is Object, not an Array. You have to create new wrapper Class (ResultsWrapper) with "results" field type of List<NewsItem>. Your method in ApiServices interface will then be: #GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage") Observable<ResultsWrapper> getResults(); That is what "Expected BEGIN_ARRAY but was BEGIN_OBJECT" says to you.
Transform a String to JSONObject
I am building an Android app that uses socket.IO to communicate with a server. On the socket I am receiving the following message: {"id":"presenterResponse","response":"accepted","sdpAnswer":"v=0\r\no=- 3689503004 3689503004 IN IP4 0.0.0.0\r\ns=Kurento Media Server\r\nc=IN IP4 0.0.0.0\r\nt=0 0\r\na=msid-semantic: WMS ARDAMS\r\na=group:BUNDLE audio video\r\nm=audio 1 UDP/TLS/RTP/SAVPF 111 0\r\na=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=mid:audio\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=rtpmap:111 opus/48000/2\r\na=rtpmap:0 PCMU/8000\r\na=setup:active\r\na=sendrecv\r\na=rtcp-mux\r\na=fmtp:111 minptime=10; useinbandfec=1\r\na=maxptime:60\r\na=ssrc:3140217435 cname:user2918705367#host-8692fd1\r\na=ice-ufrag:aYIP\r\na=ice-pwd:sKftuHNg7pyX0FocNO0qh/\r\na=fingerprint:sha-256 33:B4:A7:4B:89:64:D2:54:AF:6B:FE:D4:5D:EF:4E:D6:AB:6F:11:B1:E7:31:87:D6:0D:22:3F:53:83:08:B7:73\r\nm=video 1 UDP/TLS/RTP/SAVPF 100\r\na=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=mid:video\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=rtpmap:100 VP8/90000\r\na=rtcp-fb:100 ccm fir\r\na=rtcp-fb:100 nack\r\na=rtcp-fb:100 nack pli\r\na=rtcp-fb:100 goog-remb\r\na=setup:active\r\na=sendrecv\r\na=rtcp-mux\r\na=ssrc:2322920152 cname:user2918705367#host-8692fd1\r\na=ice-ufrag:aYIP\r\na=ice-pwd:sKftuHNg7pyX0FocNO0qh/\r\na=fingerprint:sha-256 33:B4:A7:4B:89:64:D2:54:AF:6B:FE:D4:5D:EF:4E:D6:AB:6F:11:B1:E7:31:87:D6:0D:22:3F:53:83:08:B7:73\r\nm=application 0 DTLS/SCTP 5000\r\na=inactive\r\na=mid:data\r\na=ice-ufrag:igJW\r\na=ice-pwd:skfFXPCVLtGwABgXg9xsMO\r\na=fingerprint:sha-256 33:B4:A7:4B:89:64:D2:54:AF:6B:FE:D4:5D:EF:4E:D6:AB:6F:11:B1:E7:31:87:D6:0D:22:3F:53:83:08:B7:73\r\n"} What I want to do now is to map this object on the following POJO class: import org.webrtc.SessionDescription; public class User { private String id; private String response; private String name; private String room; private String email; private String sdpOffer; private SessionDescription sdpAnswer; private String userType; public User(){}; public SessionDescription getSdpAnswer() { return sdpAnswer; } public void setSdpAnswer(SessionDescription sdpAnswer) { this.sdpAnswer = sdpAnswer; } public String getResponse() { return response; } public void setResponse(String response) { this.response = response; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getSdpOffer() { return sdpOffer; } public void setSdpOffer(String sdpOffer) { this.sdpOffer = sdpOffer; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRoom() { return room; } public void setRoom(String room) { this.room = room; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } So far I have tried to transform the message in a JSONObject JSONObject j = new JSONObject(message); and populate my own object from the JSONObject but it didn't work. How can I map the string on User class? EDIT: the message comes over socket.IO from a Node.js server in this way: In the node server I send the message by send.("new message",JSON.stringfy("sdpAnswer":sdpAnswer)); On the android client I read it like: LoginActivity.mSocket.on("new message", new Emitter.Listener() { #Override public void call(Object... args) { Log.i( TAG, "message back:received "); JSONObject j = new JSONObject(args[0]); // this throws an error Object = new JSONObject(args[0].toString()); Log.i(TAG, "The received string is " + obj.toString()); //this throws java.lang.error can not convert from string to json object } )};
use Gson String jsonString = "{jsonstringhere}"; User user= new Gson().fromJson(jsonString, User.class);
Use Gson library. Add dependency to build.gradle file. compile 'com.google.code.gson:gson:2.8.0' And parse json to object: Gson gson = new Gson(); User user= gson.fromJson(message, User.class);
Cannot Parse a JSON response that is received by RestTemplate
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); }
Using GSON giving error expected BEGIN_ARRAY but was STRING
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.