The result variable contains corrected parsed JSON.
But after deserialization List contains correct amount of items but all of them are empty.
How to fix it?
Gson gson = new Gson();
List<UnitView> unitViews = new ArrayList<UnitView>();
// https://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type
Type typeToken = new TypeToken<List<UnitView>>() { }.getType();
unitViews = gson.fromJson(result,typeToken);
Even if I do like
UnitView[] unitViews = gson.fromJson(result, UnitView[].class);
The fields of items are empty as well.
UnitView
public class UnitView implements Serializable {
public String id ;
public String name ;
public String description ;
public String deviceTypeName ;
public String categoryID ;
public String lastOnline ;
public String latitude ;
public String longitude ;
public String atTime ;
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getDeviceTypeName() {
return deviceTypeName;
}
public String getCategoryID() {
return categoryID;
}
public String getLastOnline() {
return lastOnline;
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
public String getAtTime() {
return atTime;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.description = description;
}
public void setDeviceTypeName(String deviceTypeName) {
this.deviceTypeName = deviceTypeName;
}
public void setCategoryID(String categoryID) {
this.categoryID = categoryID;
}
public void setLastOnline(String lastOnline) {
this.lastOnline = lastOnline;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public void setAtTime(String atTime) {
this.atTime = atTime;
}
}
JSON DATA
[{"ID":"294","Name":"Foton Tunland № F110","Description":null,"DeviceTypeName":"Техника ТО","CategoryID":"18","LastOnline":"19.12.2017 20:38:04","Latitude":"11,40119","Longitude":"11,42403","AtTime":"19.12.2017 20:38:04"},{"ID":"295","Name":"DML LP1200 № 9793","Description":null,"DeviceTypeName":"Буровой станок дизельный","CategoryID":"15","LastOnline":null,"Latitude":null,"Longitude":null,"AtTime":null}]
Ok , the problem is that the parser is case-sensitive, you can change the name of your attributes to match the name of the json value of you could use the SerializedName annotation like this:
#SerializedName("ID")
public String id ;
#SerializedName("Name")
public String name ;
#SerializedName("Description")
public String description;
...
or
public String ID ;
public String Name ;
public String Description ;
...
I think you're having this problem because of null values in your json.
Check it. Source
Related
java.lang.IllegalArgumentException: Only one HTTP method is allowed. Found: GET and PUT.
for method ApiInterface.UpdateCoordinates
i have tried for the last 2 hours to update the coordinates but it ain't working keeps throwing this error
java.lang.IllegalArgumentException: Only one HTTP method is allowed. Found: GET and PUT.
for method ApiInterface.UpdateCoordinates
at retrofit2.Utils.methodError(Utils.java:52)
at retrofit2.Utils.methodError(Utils.java:42)
at retrofit2.RequestFactory$Builder.parseHttpMethodAndPath(RequestFactory.java:251)
at retrofit2.RequestFactory$Builder.parseMethodAnnotation(RequestFactory.java:224)
at retrofit2.RequestFactory$Builder.build(RequestFactory.java:171)
at retrofit2.RequestFactory.parseAnnotations(RequestFactory.java:67)
at retrofit2.ServiceMethod.parseAnnotations(ServiceMethod.java:26)
at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:170)
at retrofit2.Retrofit$1.invoke(Retrofit.java:149)
at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
at $Proxy0.UpdateCoordinates(Unknown Source)
at com.example.charlo.jkuat_mobile_app.util.LocationService$1.onLocationResult(LocationService.java:54)
Model classes
the update model class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class GpsUpdate {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("data")
#Expose
private Data data;
#SerializedName("message")
#Expose
private String message;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
model class
the data model class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Data {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("driverid")
#Expose
private Integer driverid;
#SerializedName("companyid")
#Expose
private Integer companyid;
#SerializedName("vehicleid")
#Expose
private Integer vehicleid;
#SerializedName("warehouseid")
#Expose
private Integer warehouseid;
#SerializedName("orders")
#Expose
private Integer orders;
#SerializedName("status")
#Expose
private Integer status;
#SerializedName("latitute")
#Expose
private String latitute;
#SerializedName("longitude")
#Expose
private String longitude;
#SerializedName("tripdate")
#Expose
private String tripdate;
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("updated_at")
#Expose
private String updatedAt;
public Data(String latitute, String longitude) {
this.latitute = latitute;
this.longitude = longitude;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getDriverid() {
return driverid;
}
public void setDriverid(Integer driverid) {
this.driverid = driverid;
}
public Integer getCompanyid() {
return companyid;
}
public void setCompanyid(Integer companyid) {
this.companyid = companyid;
}
public Integer getVehicleid() {
return vehicleid;
}
public void setVehicleid(Integer vehicleid) {
this.vehicleid = vehicleid;
}
public Integer getWarehouseid() {
return warehouseid;
}
public void setWarehouseid(Integer warehouseid) {
this.warehouseid = warehouseid;
}
public Integer getOrders() {
return orders;
}
public void setOrders(Integer orders) {
this.orders = orders;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getLatitute() {
return latitute;
}
public void setLatitute(String latitute) {
this.latitute = latitute;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getTripdate() {
return tripdate;
}
public void setTripdate(String tripdate) {
this.tripdate = tripdate;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
}
Interface
interface class
#PUT("update_driver/{dispatchid}?")
Call<GpsUpdate> UpdateCoordinates(#Path("dispatchid") int id, #Field("latitude") String latitude, #Field("longitude") String longitude );
location service class
the update class which sends the coordinates to the backend
#Override
public void onCreate() {
super.onCreate();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
service = ApiClient.createService(ApiInterface.class);
locationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
double lat = locationResult.getLastLocation().getLatitude();
double lng = locationResult.getLastLocation().getLongitude();
String latitude = String.valueOf(lat);
String longitude = String.valueOf(lng);
Data data = new Data(latitude,longitude);
Call<GpsUpdate> call = service.UpdateCoordinates(tokenManager.getToken().getDispatchid(),data.getLatitute(), data.getLongitude());
call.enqueue(new Callback<GpsUpdate>() {
#Override
public void onResponse(Call<GpsUpdate> call, Response<GpsUpdate> response) {
}
#Override
public void onFailure(Call<GpsUpdate> call, Throwable t) {
}
});
I think I should have marked this as a duplicate:
Retrofit: how fix "only one http method is allowed. found: get and get"?
Try changing the
#Path("dispatchid") int id
to
#Path("dispatchid") int dispatchid
I have a model below which i use to add my data and get it's properties when a user selects an option. Unfortunately i am unable to get the logic right. Kindly help with the best way to set data to a model using an array.
Unfortunately i get the error Data cannot be applied to Data[]
Model
public class Data
{
private String isVerified;
private String providerType;
private String modifiedAt;
private String modifiedBy;
private String provider;
private String id;
private String accountNumber;
private String accountName;
private String createdBy;
private String isDefault;
private String createdAt;
private String userId;
private String providerId;
public String getIsVerified ()
{
return isVerified;
}
public void setIsVerified (String isVerified)
{
this.isVerified = isVerified;
}
public String getProviderType ()
{
return providerType;
}
public void setProviderType (String providerType)
{
this.providerType = providerType;
}
public String getModifiedAt ()
{
return modifiedAt;
}
public void setModifiedAt (String modifiedAt)
{
this.modifiedAt = modifiedAt;
}
public String getModifiedBy ()
{
return modifiedBy;
}
public void setModifiedBy (String modifiedBy)
{
this.modifiedBy = modifiedBy;
}
public String getProvider ()
{
return provider;
}
public void setProvider (String provider)
{
this.provider = provider;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getAccountNumber ()
{
return accountNumber;
}
public void setAccountNumber (String accountNumber)
{
this.accountNumber = accountNumber;
}
public String getAccountName ()
{
return accountName;
}
public void setAccountName (String accountName)
{
this.accountName = accountName;
}
public String getCreatedBy ()
{
return createdBy;
}
public void setCreatedBy (String createdBy)
{
this.createdBy = createdBy;
}
public String getIsDefault ()
{
return isDefault;
}
public void setIsDefault (String isDefault)
{
this.isDefault = isDefault;
}
public String getCreatedAt ()
{
return createdAt;
}
public void setCreatedAt (String createdAt)
{
this.createdAt = createdAt;
}
public String getUserId ()
{
return userId;
}
public void setUserId (String userId)
{
this.userId = userId;
}
public String getProviderId ()
{
return providerId;
}
public void setProviderId (String providerId)
{
this.providerId = providerId;
}
#Override
public String toString()
{
return "ClassPojo [isVerified = "+isVerified+", providerType = "+providerType+", modifiedAt = "+modifiedAt+", modifiedBy = "+modifiedBy+", provider = "+provider+", id = "+id+", accountNumber = "+accountNumber+", accountName = "+accountName+", createdBy = "+createdBy+", isDefault = "+isDefault+", createdAt = "+createdAt+", userId = "+userId+", providerId = "+providerId+"]";
}
}
Below is my method to add data to the model
private void addToWallets(Data walletData) {
Data wallet = new Data();
wallet.setId(walletData.getId());
wallet.setAccountNumber(walletData.getAccountNumber());
wallets.add(wallet);
}
I add the response from the server to my method that i created to add data to the model:
if (response.isSuccess()){
loading.dismiss();
Data[] wallets = response.body().getData();
addToWallets(wallets);
}
An array of Data can't be converted to a single Data object.
I suppose that this is what you want:
Data[] wallets = response.body().getData();
for (Data wallet : wallets) {
addToWallets(wallet);
}
ObjectMapper mapper = new ObjectMapper();
try {
attractionMainResponse = mapper.readValue(response,AttractionMainResponse.class);
} catch(IOException io) {
showToast("Something went wrong");
FirebaseCrash.log(io.toString());
finish();
}
AttractionMainResponse :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionMainResponse {
private AttractionDetailModel Attraction_Info;
private String response;
public AttractionMainResponse() {
Attraction_Info = null;
response =null;
}
public AttractionMainResponse(AttractionDetailModel aa,String ab) {
Attraction_Info = aa;
response = ab;
}
public AttractionDetailModel getAttraction_Info() {
return Attraction_Info;
}
public void setAttraction_Info(AttractionDetailModel attraction_Info) {
Attraction_Info = attraction_Info;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
AttractionDetailModel :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionDetailModel {
private AddressDataAttraction address_data;
private List<Image> Images;
private TypesInAttraction Type;
private String architect;
private String architectural_style;
private int city_id;
private String founder;
private String description;
private int id;
private String name;
private String height;
private String opened_since;
private String popularity;
private String timings;
private String visitors;
private String profile_image_url;
public AttractionDetailModel() {
address_data = null;
architect = null;
architectural_style = null;
city_id=-1;
founder = null;
description = null;
id=-1;
name=null;
height=null;
opened_since=null;
popularity = null;
timings=null;
visitors=null;
Images = null;
Type=null;
profile_image_url=null;
}
public AttractionDetailModel(AddressDataAttraction address_data, List<Image> images, TypesInAttraction type, String architect, String architectural_style, int city_id, String founder, String description, int id, String name, String height, String opened_since, String popularity, String timings, String visitors, String profile_image_url) {
this.address_data = address_data;
Images = images;
Type = type;
this.architect = architect;
this.architectural_style = architectural_style;
this.city_id = city_id;
this.founder = founder;
this.description = description;
this.id = id;
this.name = name;
this.height = height;
this.opened_since = opened_since;
this.popularity = popularity;
this.timings = timings;
this.visitors = visitors;
this.profile_image_url = profile_image_url;
}
public String getProfile_image_url() {
return profile_image_url;
}
public void setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public AddressDataAttraction getAddress_data() {
return address_data;
}
public void setAddress_data(AddressDataAttraction address_data) {
this.address_data = address_data;
}
public List<Image> getImages() {
return Images;
}
public void setImages(List<Image> images) {
Images = images;
}
public TypesInAttraction getType() {
return Type;
}
public void setType(TypesInAttraction type) {
Type = type;
}
public String getArchitect() {
return architect;
}
public void setArchitect(String architect) {
this.architect = architect;
}
public String getArchitectural_style() {
return architectural_style;
}
public void setArchitectural_style(String architectural_style) {
this.architectural_style = architectural_style;
}
public int getCity_id() {
return city_id;
}
public void setCity_id(int city_id) {
this.city_id = city_id;
}
public String getFounder() {
return founder;
}
public void setFounder(String founder) {
this.founder = founder;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getOpened_since() {
return opened_since;
}
public void setOpened_since(String opened_since) {
this.opened_since = opened_since;
}
public String getPopularity() {
return popularity;
}
public void setPopularity(String popularity) {
this.popularity = popularity;
}
public String getTimings() {
return timings;
}
public void setTimings(String timings) {
this.timings = timings;
}
public String getVisitors() {
return visitors;
}
public void setVisitors(String visitors) {
this.visitors = visitors;
}
}
AddressDataAttractions :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AddressDataAttraction {
private String address;
private String city;
private String country;
private String landmark;
private float latitude;
private float longitude;
private String pincode;
private String state;
public AddressDataAttraction() {
address=null;
city=null;
country=null;
landmark=null;
latitude=-1;
longitude=-1;
pincode=null;
state=null;
}
public AddressDataAttraction(String address, String city, String country, String landmark, float latitude, float longitude, String pincode, String state) {
this.address = address;
this.city = city;
this.country = country;
this.landmark = landmark;
this.latitude = latitude;
this.longitude = longitude;
this.pincode = pincode;
this.state = state;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
TypeInAttraction :
#JsonIgnoreProperties (ignoreUnknown = true)
public class TypesInAttraction{
private String type;
private int id ;
public TypesInAttraction() {
type=null;
id=-1;
}
public TypesInAttraction(String type, int id) {
this.type = type;
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
In debug mode, string response in objectMapper shows correct response, string response in attractionMainResponse giving a success but can't map the attractionDetailModel, giving null.
Is this about a Jackson ObjectMapper? Is it possible to create a smaller example, that makes it easier to give a solution.
How get value in array "rate" to invoke getters methods ?
My Json response is something as below and confused how to parse it using GSON. Please have look on the following and guide me how i can parse it using GSON.
data.json
{
"query":{
"count":2,
"created":"2017-01-03T12:45:19Z",
"lang":"en-us",
"results":{
"rate":[
{
"id":"BTC/USD",
"Name":"BTCUSD",
"Rate":"985.50",
"Date":"1/3/2017",
"Time":"10:35am",
"Ask":"985.50",
"Bid":"985.35"
},
{
"id":"BTC/EUR",
"Name":"BTCEUR",
"Rate":"973.16",
"Date":"1/3/2017",
"Time":"10:35am",
"Ask":"973.16",
"Bid":"973.10"
}
]
}
}
}
I use classes to parse apart
Market.java
public class Market {
#SerializedName("query")
private Query query;
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
}
Query.java
public class Query {
#SerializedName("count")
private Integer count;
#SerializedName("created")
private String created;
#SerializedName("lang")
private String lang;
#SerializedName("results")
private Results results;
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public Results getResults() {
return results;
}
public void setResults(Results results) {
this.results = results;
}
}
Rate.java
public class Rate {
#SerializedName("id")
private String id;
#SerializedName("Name")
private String name;
#SerializedName("Rate")
private String rate;
#SerializedName("Date")
private String date;
#SerializedName("Time")
private String time;
#SerializedName("Ask")
private String ask;
#SerializedName("Bid")
private String bid;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getAsk() {
return ask;
}
public void setAsk(String ask) {
this.ask = ask;
}
public String getBid() {
return bid;
}
public void setBid(String bid) {
this.bid = bid;
}
}
Results.java
public class Results {
#SerializedName("rate")
private List<Rate> rate = null;
public List<Rate> getRate() {
return rate;
}
public void setRate(List<Rate> rate) {
this.rate = rate;
}
}
Trying to get the values
Main.java
public class Main {
/* ..... */
Gson gson = new Gson();
Market market = gson.fromJson(json, Market.class);
//error: incompatible types: Rate cannot be converted to List<Rate>
for( List<Rate> res : market.getQuery().getResults().getRate());
{
Log.v(LOG_TAG, res); // error: cannot find symbol variable res
}
}
how to do it properly ?
The syntax of your for each loop is incorrect. Since you are attempting to loop through a list of Rate objects, the type of res should be a Rate, not a list of Rates:
for (Rate res : market.getQuery().getResults().getRate()) {
// code here
}
As an aside, you should consider checking for null values before dereferencing all of those child objects as you run the risk of throwing a NullPointerException at runtime.
I am trying to get some the array of actors from Jira. The code for the wrapper is used in a Gson.fromJson call. I had used something similar with a json string that did not have an array in it that had the information I needed and it worked fine, so the issue seems to do with the array, but I am not 100% sure:
import com.google.gson.annotations.SerializedName;
public class JiraRoleJsonWrapper {
#SerializedName("self")
private String self;
#SerializedName("name")
private String name;
#SerializedName("id")
private int id;
#SerializedName("description")
private String description;
#SerializedName("actors")
private JiraActors[] actors;
public JiraActors[] getActors() {
return actors;
}
public void setActors(JiraActors[] actors) {
this.actors = actors;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String key) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
public String[] getAvatarUrls() {
return avatarUrls;
}
public void setAvatarUrls(String[] avatarUrls) {
this.avatarUrls = avatarUrls;
}
*/
}
class JiraActors {
#SerializedName("id")
private int id;
#SerializedName("displayNme")
private String displayName;
#SerializedName("type")
private String type;
#SerializedName("name")
private String name;
//#SerializedName("avatarUrl")
//private String avatarUrl;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The json it would receive:
{
"self":"http://someserver.com:8080/apps/jira/rest/api/2/project/10741/role/10002",
"name":"Administrators",
"id":10002,
"description":"A project role",
"actors":[
{
"id":12432,
"displayName":"Joe Smith",
"type":"atlassian-user-role-actor",
"name":"joesmi",
"avatarUrl":"/apps/jira/secure/useravatar?size=xsmall&ownerId=dawsmi&avatarId=12245"
},
{
"id":12612,
"displayName":"Smurfette Desdemona",
"type":"atlassian-user-role-actor",
"name":"smudes",
"avatarUrl":"/apps/jira/secure/useravatar?size=xsmall&ownerId=lamade&avatarId=10100"
},
This shows two actors and the format of the json. Please note I did not put a complete json response. It just shows two actors.
In my code, I tried the following to retrieve the actors:
InputStream is = response.getEntityInputStream();
Reader reader = new InputStreamReader(is);
Gson gson = new Gson();
JiraRoleJsonWrapper[] jiraRoleJsonWrapper = gson.fromJson(reader, JiraRoleJsonWrapper[].class);
for (JiraRoleJsonWrapper w : jiraRoleJsonWrapper) {
JiraActors[] a = w.getActors();
String name = a.getName();
It does not find getName for some reason. I am not sure why.
I figured it out.
I change the setActors to
public void setActors(ArrayList<JiraActors> actors) {
this.actors = actors;
}
Then I was able to get the array list and get access to the getName() method of JiraActors.