Using GSON giving error expected BEGIN_ARRAY but was STRING - java

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.

Related

Mapping a nested JSON response obtained using RxJava and Retrofit

I starting out with RxJava and Retrofit and wanted to create a simple app to show a list of 100 cryptocurrencies.
I am making an api call which results in something like this :
{
"Response": "Success",
"Message": "Coin list succesfully returned!",
"BaseImageUrl": "https://www.cryptocompare.com",
"BaseLinkUrl": "https://www.cryptocompare.com",
"Data": {
"LTC": {
"Id": "3808",
"Url": "/coins/ltc/overview",
"ImageUrl": "/media/19782/ltc.png",
"Name": "LTC",
"CoinName": "Litecoin",
"FullName": "Litecoin (LTC)",
"Algorithm": "Scrypt",
"ProofType": "PoW",
"SortOrder": "2"
}
...
},
"Type": 100
}
But all I want from this is "Response" and "Data". Since it is not practical to create a 100 different model classes for each coin, I want to store information of all the coins in a common class named Coin which would look something like this :
public class Coins {
#SerializedName("Algorithm")
private String mAlgorithm;
#SerializedName("CoinName")
private String mCoinName;
#SerializedName("FullName")
private String mFullName;
#SerializedName("FullyPremined")
private String mFullyPremined;
#SerializedName("Id")
private String mId;
#SerializedName("ImageUrl")
private String mImageUrl;
#SerializedName("Name")
private String mName;
#SerializedName("PreMinedValue")
private String mPreMinedValue;
#SerializedName("ProofType")
private String mProofType;
#SerializedName("SortOrder")
private String mSortOrder;
#SerializedName("Sponsored")
private Boolean mSponsored;
#SerializedName("Symbol")
private String mSymbol;
#SerializedName("TotalCoinSupply")
private String mTotalCoinSupply;
#SerializedName("TotalCoinsFreeFloat")
private String mTotalCoinsFreeFloat;
#SerializedName("Url")
private String mUrl;
public String getAlgorithm() {
return mAlgorithm;
}
public void setAlgorithm(String Algorithm) {
mAlgorithm = Algorithm;
}
public String getCoinName() {
return mCoinName;
}
public void setCoinName(String CoinName) {
mCoinName = CoinName;
}
public String getFullName() {
return mFullName;
}
public void setFullName(String FullName) {
mFullName = FullName;
}
public String getFullyPremined() {
return mFullyPremined;
}
public void setFullyPremined(String FullyPremined) {
mFullyPremined = FullyPremined;
}
public String getId() {
return mId;
}
public void setId(String Id) {
mId = Id;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String ImageUrl) {
mImageUrl = ImageUrl;
}
public String getName() {
return mName;
}
public void setName(String Name) {
mName = Name;
}
public String getPreMinedValue() {
return mPreMinedValue;
}
public void setPreMinedValue(String PreMinedValue) {
mPreMinedValue = PreMinedValue;
}
public String getProofType() {
return mProofType;
}
public void setProofType(String ProofType) {
mProofType = ProofType;
}
public String getSortOrder() {
return mSortOrder;
}
public void setSortOrder(String SortOrder) {
mSortOrder = SortOrder;
}
public Boolean getSponsored() {
return mSponsored;
}
public void setSponsored(Boolean Sponsored) {
mSponsored = Sponsored;
}
public String getSymbol() {
return mSymbol;
}
public void setSymbol(String Symbol) {
mSymbol = Symbol;
}
public String getTotalCoinSupply() {
return mTotalCoinSupply;
}
public void setTotalCoinSupply(String TotalCoinSupply) {
mTotalCoinSupply = TotalCoinSupply;
}
public String getTotalCoinsFreeFloat() {
return mTotalCoinsFreeFloat;
}
public void setTotalCoinsFreeFloat(String TotalCoinsFreeFloat) {
mTotalCoinsFreeFloat = TotalCoinsFreeFloat;
}
public String getUrl() {
return mUrl;
}
public void setUrl(String Url) {
mUrl = Url;
}
}
So finally my mapped response class would look like :
public class CoinsListResponse {
private boolean success;
private List<Coins> coinsList;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public List<Coins> getCoinsList() {
return coinsList;
}
public void setCoinsList(List<Coins> coinsList) {
this.coinsList = coinsList;
}
}
I haven't added #Serialized notations because I don't know what key to annotate it with.
My Retrofit service interface has a method to return the results to this map :
public interface CoinService {
#NonNull
#POST
Observable<CoinsListResponse> getCoinList();
}
Since, I am a starter with Retrofit and RxAndroid, there might be a better method to do this, which I am not aware of. If so, please mention that as well !! I am trying to get my head around this for days but couldn't find any answer on SO as well.
Please Help !!
Change
private List<Coins> coinsList;
to
#SerializedName("Data")
private Map<String, Coins> coinsByName;
You can then either just use coinsByName.values() or call e.g. coinsByName.get("LTC")

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

Object become null when converted to json

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!

Looping through Multiple JSON Objects in Android

I'm trying to parse a JSON object, part of which looks like this :
{
"status":{
"rcode":200,
"message":"OK"
},
"data":{
"0":{
"SubFranchiseID":"0",
"OutletID":"607",
"OutletName":"Spill ",
"BrandID":"403",
"Address":"J-349, JP Road, Opp. Apna Bazar, JP Rd, D.N.Nagar, Andheri West, Mumbai, Maharashtra, India",
"NeighbourhoodID":"1",
"CityID":"1",
"Email":null,
"Timings":"Everyday: 6 pm to 1:30 am.",
"CityRank":null,
"Latitude":"19.127473",
"Longitude":"72.832545",
"Pincode":null,
"Landmark":null,
"Streetname":null,
"BrandName":"Spill ",
"OutletURL":"https:\/\/plus.google.com\/111539701326240643109\/about?hl=en-US",
"NumCoupons":1,
"NeighbourhoodName":"Andheri West",
"PhoneNumber":"+91 22 2642 5895",
"CityName":"Mumbai",
"Distance":8205.2235,
"Categories":[
{
"OfflineCategoryID":"32",
"Name":"Continental",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"13",
"Name":"Bar and Restaurant",
"ParentCategoryID":"1",
"CategoryType":"TypeOfRestaurant"
},
{
"OfflineCategoryID":"17",
"Name":"Italian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"1",
"Name":"Restaurant",
"ParentCategoryID":null,
"CategoryType":""
},
{
"OfflineCategoryID":"21",
"Name":"North Indian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
}
],
"LogoURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/logo_403.jpg",
"CoverURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/cover_607.jpg"
},
"1 "{
"SubFranchiseID":"1",
"OutletID":"60",
"OutletName":"Bill ",
.
.
.
}
}
There are nearly 35 Json objects and nested JsonArrays for each of these objects.I'm trying to get data like this :
url = new URL(uri);
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
json =sb.toString();
JSONObject sjson=json.getJSONObject("data");
Log.d("sjson values-->",sjson+"--");
**JSONObject ssjson=sjson.getJSONObject("0");**
And now i am getting each of values like this :
String outletName = ssjson.getString("OutletName");
My question is there any better way (loop) through all objects ( 0,1,...35) and get data for each individual object separately.
Example json
{
"status": {
"rcode": "200",
"message": "Good, you got me!!!"
},
"data": [
{
"SubFranchiseID": "0",
"OutletID": "607",
"OutletName": "Spill",
},
{
"SubFranchiseID": "0",
"OutletID": "607",
"OutletName": "Spill"
}
]
}
Represent the json in terms of plain java classes with getter and
setters
First create a the root class (for the root object)
public class Root {
//For the status object
private Status status;
//For the array of data objects
private List<Data> data;
//create setters and getters for the two properties.
}
public class Status {
private String rcode;
//this maps to the rcode in the status object in json
private String message;
//create setters and getters for the two
}
public class Data {
private String SubFranchiseID;
private String OutletID;
private String OutletName;
//create setters and getters for these properties.
}
Now, lets do the magic with gson (The serialization of the json in to the ready made classes)
reader.close();
json =sb.toString();
Root root = new Gson().fromJson(response, Root.class);
//get the rcode
if(root.getStatus().getrCode().equalsIgnoreCase("200"))
{
//print the data.
for(Data d : root.getData()) {
System.out.println(d.getSubFranchiseID()+"-"+d.getOutletID()+"-"+d.getOutletName());
}
}
A small note for using gson.
1.) The property names inside the classes should match the property in the json or else use a `#SerializeName("propertyname")`.
2.) An array of objects would map to List<YourObject> , for eg : the data property in the json.
3.) You can have default value for your properties without creating getters and setters for them like
private boolean isJson = true;
Thanks for the help. I have a lot of json objects inside "data" -> "0" like "Outletname","OutletID ",etc , before Json Array ( "Categories" ). i have created a model class for my data. Now i want to itterate json objects data using Gson.Part of my json data
"0":{
"SubFranchiseID":"0",
"OutletID":"607",
"OutletName":"Spill ",
"BrandID":"403",
"Address":"J-349, JP Road, Opp. Apna Bazar, JP Rd, D.N.Nagar, Andheri West, Mumbai, Maharashtra, India",
"NeighbourhoodID":"1",
"CityID":"1",
"Email":null,
"Timings":"Everyday: 6 pm to 1:30 am.",
"CityRank":null,
"Latitude":"19.127473",
"Longitude":"72.832545",
"Pincode":null,
"Landmark":null,
"Streetname":null,
"BrandName":"Spill ",
"OutletURL":"https:\/\/plus.google.com\/111539701326240643109\/about?hl=en-US",
"NumCoupons":1,
"NeighbourhoodName":"Andheri West",
"PhoneNumber":"+91 22 2642 5895",
"CityName":"Mumbai",
"Distance":8205.2235,
"Categories":[
{
"OfflineCategoryID":"32",
"Name":"Continental",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"13",
"Name":"Bar and Restaurant",
"ParentCategoryID":"1",
"CategoryType":"TypeOfRestaurant"
},
{
"OfflineCategoryID":"17",
"Name":"Italian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"1",
"Name":"Restaurant",
"ParentCategoryID":null,
"CategoryType":""
},
{
"OfflineCategoryID":"21",
"Name":"North Indian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
}
],
"LogoURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/logo_403.jpg",
"CoverURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/cover_607.jpg"
},
}
My java Model Class :
/**
* SubFranchiseID : 0
* OutletID : 607
* OutletName : Spill
* BrandID : 403
* Address : J-349, JP Road, Opp. Apna Bazar, JP Rd, D.N.Nagar, Andheri West, Mumbai, Maharashtra, India
* NeighbourhoodID : 1
* CityID : 1
* Email : null
* Timings : Everyday: 6 pm to 1:30 am.
* CityRank : null
* Latitude : 19.127473
* Longitude : 72.832545
* Pincode : null
* Landmark : null
* Streetname : null
* BrandName : Spill
* OutletURL : https://plus.google.com/111539701326240643109/about?hl=en-US
* NumCoupons : 1
* NeighbourhoodName : Andheri West
* PhoneNumber : +91 22 2642 5895
* CityName : Mumbai
* Distance : 8205.2235
* Categories : [{"OfflineCategoryID":"32","Name":"Continental","ParentCategoryID":"1","CategoryType":"Cuisine"},{"OfflineCategoryID":"13","Name":"Bar and Restaurant","ParentCategoryID":"1","CategoryType":"TypeOfRestaurant"},{"OfflineCategoryID":"17","Name":"Italian","ParentCategoryID":"1","CategoryType":"Cuisine"},{"OfflineCategoryID":"1","Name":"Restaurant","ParentCategoryID":null,"CategoryType":""},{"OfflineCategoryID":"21","Name":"North Indian","ParentCategoryID":"1","CategoryType":"Cuisine"}]
* LogoURL : http://www.google.in/sitespecific/media/generated/offlineimages/logo_403.jpg
* CoverURL : http://www.google.in/sitespecific/media/generated/offlineimages/cover_607.jpg
*/
public static class OutletDetailsEntity {
private String SubFranchiseID;
private String OutletID;
private String OutletName;
private String BrandID;
private String Address;
private String NeighbourhoodID;
private String CityID;
private Object Email;
private String Timings;
private Object CityRank;
private String Latitude;
private String Longitude;
private Object Pincode;
private Object Landmark;
private Object Streetname;
private String BrandName;
private String OutletURL;
private int NumCoupons;
private String NeighbourhoodName;
private String PhoneNumber;
private String CityName;
private double Distance;
private String LogoURL;
private String CoverURL;
private List<CategoriesEntity> Categories;
public void setSubFranchiseID(String SubFranchiseID) {
this.SubFranchiseID = SubFranchiseID;
}
public void setOutletID(String OutletID) {
this.OutletID = OutletID;
}
public void setOutletName(String OutletName) {
this.OutletName = OutletName;
}
public void setBrandID(String BrandID) {
this.BrandID = BrandID;
}
public void setAddress(String Address) {
this.Address = Address;
}
public void setNeighbourhoodID(String NeighbourhoodID) {
this.NeighbourhoodID = NeighbourhoodID;
}
public void setCityID(String CityID) {
this.CityID = CityID;
}
public void setEmail(Object Email) {
this.Email = Email;
}
public void setTimings(String Timings) {
this.Timings = Timings;
}
public void setCityRank(Object CityRank) {
this.CityRank = CityRank;
}
public void setLatitude(String Latitude) {
this.Latitude = Latitude;
}
public void setLongitude(String Longitude) {
this.Longitude = Longitude;
}
public void setPincode(Object Pincode) {
this.Pincode = Pincode;
}
public void setLandmark(Object Landmark) {
this.Landmark = Landmark;
}
public void setStreetname(Object Streetname) {
this.Streetname = Streetname;
}
public void setBrandName(String BrandName) {
this.BrandName = BrandName;
}
public void setOutletURL(String OutletURL) {
this.OutletURL = OutletURL;
}
public void setNumCoupons(int NumCoupons) {
this.NumCoupons = NumCoupons;
}
public void setNeighbourhoodName(String NeighbourhoodName) {
this.NeighbourhoodName = NeighbourhoodName;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
public void setCityName(String CityName) {
this.CityName = CityName;
}
public void setDistance(double Distance) {
this.Distance = Distance;
}
public void setLogoURL(String LogoURL) {
this.LogoURL = LogoURL;
}
public void setCoverURL(String CoverURL) {
this.CoverURL = CoverURL;
}
public void setCategories(List<CategoriesEntity> Categories) {
this.Categories = Categories;
}
public String getSubFranchiseID() {
return SubFranchiseID;
}
public String getOutletID() {
return OutletID;
}
public String getOutletName() {
return OutletName;
}
public String getBrandID() {
return BrandID;
}
public String getAddress() {
return Address;
}
public String getNeighbourhoodID() {
return NeighbourhoodID;
}
public String getCityID() {
return CityID;
}
public Object getEmail() {
return Email;
}
public String getTimings() {
return Timings;
}
public Object getCityRank() {
return CityRank;
}
public String getLatitude() {
return Latitude;
}
public String getLongitude() {
return Longitude;
}
public Object getPincode() {
return Pincode;
}
public Object getLandmark() {
return Landmark;
}
public Object getStreetname() {
return Streetname;
}
public String getBrandName() {
return BrandName;
}
public String getOutletURL() {
return OutletURL;
}
public int getNumCoupons() {
return NumCoupons;
}
public String getNeighbourhoodName() {
return NeighbourhoodName;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public String getCityName() {
return CityName;
}
public double getDistance() {
return Distance;
}
public String getLogoURL() {
return LogoURL;
}
public String getCoverURL() {
return CoverURL;
}

Exception in JSON parsing: Expected BEGIN_ARRAY but was BEGIN_OBJECT?

I am trying to parse the JSON response from this link and I'm getting this exception:
Expected BEGIN_ARRAY but was BEGIN_OBJECT
I have created this class to encapsulate the JSON data:
public class PlacesTextSearch {
private String icon;
private String name;
private String types;
private String formatted_address;
private double latitude;
private double longitude;
private String id;
public PlacesTextSearch(String icon,String name,String types,String formatted_address,double latitude,double longitude) {
// TODO Auto-generated constructor stub
setIcon(icon);
setName(name);
setTypes(types);
setFormatted_address(formatted_address);
setLatitude(latitude);
setLongitude(longitude);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTypes() {
return types;
}
public void setTypes(String types) {
this.types = types;
}
public String getFormatted_address() {
return formatted_address;
}
public void setFormatted_address(String formatted_address) {
this.formatted_address = formatted_address;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
}
And this is my code to parse the JSON:
private ArrayList<PlacesTextSearch> arrayListPlaces;
Type listType = new TypeToken<ArrayList<PlacesTextSearch>>(){}.getType();
arrayListPlaces=new Gson().fromJson(response,listType);
Here you can see the complete exception stacktrace:
Have you read Gson documentation before trying to write your code? Have you even taken a look at JSON structures?
Your code has many errors... The point is that you have to create a Java class structure that matches your JSON structure. And in fact, your class structure is not even similar to the JSON you want to parse! Basically where there's an object { } in your JSON you have to use a class, and where there's an array in your JSON [ ] you have to use an array or a List...
According to your PlacesTextSearch class, I guess the JSON piece you want to parse is:
{
...,
"results" : [
{
"formatted_address" : "Zeytinlik Mh., Bakırköy/İstanbul, Türkiye",
"geometry" : {
"location" : {
"lat" : 40.9790040,
"lng" : 28.8730110
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "e520b6e19bae5c014470989f9d3405e55dce5155",
"name" : "PTT",
"types" : [ "post_office", "finance", "establishment" ]
...
},
...
],
...
}
So, how do you pretend to parse this into an ArrayList<PlacesTextSearch>!? That's not what your JSON represents! Do you really not see it?
Try something like this class structure (pseudo-code):
class Response
List<PlacesTextSearch> results;
class PlacesTextSearch
String formatted_address;
Geometry geometry;
String icon;
String id;
String name;
List<String> types;
class Geometry
Location location;
class Location
long lat;
long lng;
And parse it with:
Response response = new Gson().fromJson(response, Response.class);

Categories