This question already has answers here:
Retrofit 2: Get JSON from Response body
(14 answers)
Closed 5 years ago.
How to read this response from retrofit and store to java class and access somewhere ??
{
"user": {
"__v": 0,
"updated_at": "2017-11-08T12:07:46.729Z",
"created_at": "2017-11-08T12:07:46.729Z",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3QzIiwidXNlcmlkIjozLCJlbWFpbCI6ImFydWwzQHRlc3QuY29tIiwiYWNjZXNzX2xldmVsIjoiQWRtaW4iLCJfaWQiOiI1YTAyZjM5Mjk5OGM4OTI3MjQxYTQ3N2YiLCJncm91cHMiOlt7ImlkIjoxLCJuYW1lIjoiZGlhbGVyIiwiX2lkIjoiNThiM2JmODI5ZTg2MDFjMDVlNzIxNjI3In1dfQ.VKEt1JoXoL_xfRDrrFK-jVj8zC23j4sqZTT2S3HGMbc",
"username": "test3",
"userid": 3,
"email": "arul3#test.com",
"access_level": "Admin",
"_id": "5a02f392998c8927241a477f",
"groups": [{
"id": 1,
"name": "dialer",
"_id": "58b3bf829e8601c05e721627"
}]
}
}
Create classes from pojo like that then parse to retrofit Convert json response to classes
public class MyPojo{
private User user;
public User getUser ()
{
return user;
}
public void setUser (User user)
{
this.user = user;
}
}
User Class:
public class User{
private String username;
private String updated_at;
private String _id;
private String access_level;
private String email;
private String token;
private String userid;
private String __v;
private String created_at;
private Groups[] groups;
public String getUsername ()
{
return username;
}
public void setUsername (String username)
{
this.username = username;
}
public String getUpdated_at ()
{
return updated_at;
}
public void setUpdated_at (String updated_at)
{
this.updated_at = updated_at;
}
public String get_id ()
{
return _id;
}
public void set_id (String _id)
{
this._id = _id;
}
public String getAccess_level ()
{
return access_level;
}
public void setAccess_level (String access_level)
{
this.access_level = access_level;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getToken ()
{
return token;
}
public void setToken (String token)
{
this.token = token;
}
public String getUserid ()
{
return userid;
}
public void setUserid (String userid)
{
this.userid = userid;
}
public String get__v ()
{
return __v;
}
public void set__v (String __v)
{
this.__v = __v;
}
public String getCreated_at ()
{
return created_at;
}
public void setCreated_at (String created_at)
{
this.created_at = created_at;
}
public Groups[] getGroups ()
{
return groups;
}
public void setGroups (Groups[] groups)
{
this.groups = groups;
}
}
Groups Class:
public class Groups{
private String id;
private String _id;
private String name;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String get_id ()
{
return _id;
}
public void set_id (String _id)
{
this._id = _id;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}}
Now follow that put your classes and get desire response Retrofit Json response
Related
I am trying to get the value of a JSON response and display it in my textView and editText. But I get a null object reference as an error.
JSON Response:
{
"srNo": 1,
"date": "11/14/2019 12:00:00 AM",
"fieldEngineer": "Angel",
"accountName": "Forever 21 Megamall",
"irNo": 1,
"joNo": 1,
"address": "Mandaluyong City",
"contactPerson": "Jansen Babon",
"designation": "",
"contactNo": "",
"email": "",
"timeIn": "00:00:00",
"timeOut": "00:00:00",
"productType": "Security",
"problem": ""
}
Java class:
private void fetchData() {
JsonObject paramObject = new JsonObject();
Call<ResObj> call = userService.userLogin(paramObject);
call.enqueue(new Callback<ResObj>() {
#Override
public void onResponse(Call<ResObj> call, retrofit2.Response<ResObj> response) {
ResObj resObj = response.body();
String srNo = resObj.getSrNo();
String date = resObj.getDate();
String fieldEngineer = resObj.getFieldEngineer();
String accountName = resObj.getAccountName();
String irNo = resObj.getIrNo();
String joNo = resObj.getJoNo();
String address = resObj.getAddress();
String contactPerson = resObj.getContactPerson();
String designation = resObj.getDesignation();
String contactNo = resObj.getContactNo();
String email = resObj.getEmail();
String timeIn = resObj.getTimeIn();
String timeOut = resObj.getTimeOut();
String productType = resObj.getProductType();
String problem = resObj.getProblem();
//the response I am getting here is null
tvSrNo.setText(srNo);
etdate.setText(date);
etfieldengineer.setText(fieldEngineer);
etaccname.setText(accountName);
etirno.setText(irNo);
etjono.setText(joNo);
JsonObject workObj = new JsonObject();
try {
workObj.addProperty("srNo", resObj.getSrNo());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResObj> call, Throwable t) {
}
});
}
I tried using this tvSrNo.setText(resObj.getSrNo()) instead of tvSrNo.setText(srNo) but it still gets the same problem.
I am also using Retrofit.
I expect the result that JSON data will be placed in an editText or textView. But apparently, the response is getting null.
ResObj class:
private String date;
private String address;
private String accountName;
private String contactPerson;
private String timeOut;
private String problem;
private String srNo;
private String fieldEngineer;
private String joNo;
private String irNo;
private String message;
private String designation;
private String email;
private String timeIn;
private String productType;
private boolean status;
private String contactNo;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getContactPerson() {
return contactPerson;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public String getTimeOut() {
return timeOut;
}
public void setTimeOut(String timeOut) {
this.timeOut = timeOut;
}
public String getProblem() {
return problem;
}
public void setProblem(String problem) {
this.problem = problem;
}
public String getSrNo() {
return srNo;
}
public void setSrNo(String srNo) {
this.srNo = srNo;
}
public String getFieldEngineer() {
return fieldEngineer;
}
public void setFieldEngineer(String fieldEngineer) {
this.fieldEngineer = fieldEngineer;
}
public String getJoNo() {
return joNo;
}
public void setJoNo(String joNo) {
this.joNo = joNo;
}
public String getIrNo() {
return irNo;
}
public void setIrNo(String irNo) {
this.irNo = irNo;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTimeIn() {
return timeIn;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.android.ras.ResObj.getSrNo()' on a null object reference
at com.example.android.ras.MainActivity$3.onResponse(MainActivity.java:187)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:71)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Change your String to Integer
public class Codebeautify {
private Integer srNo;
private String date;
private String fieldEngineer;
private String accountName;
private Integer irNo;
private Integer joNo;
private String address;
private String contactPerson;
private String designation;
private String contactNo;
private String email;
private String timeIn;
private String timeOut;
private String productType;
private String problem;
// Getter Methods
public Integer getSrNo() {
return srNo;
}
public String getDate() {
return date;
}
public String getFieldEngineer() {
return fieldEngineer;
}
public String getAccountName() {
return accountName;
}
public Integer getIrNo() {
return irNo;
}
public Integer getJoNo() {
return joNo;
}
public String getAddress() {
return address;
}
public String getContactPerson() {
return contactPerson;
}
public String getDesignation() {
return designation;
}
public String getContactNo() {
return contactNo;
}
public String getEmail() {
return email;
}
public String getTimeIn() {
return timeIn;
}
public String getTimeOut() {
return timeOut;
}
public String getProductType() {
return productType;
}
public String getProblem() {
return problem;
}
// Setter Methods
public void setSrNo(Integer srNo) {
this.srNo = srNo;
}
public void setDate(String date) {
this.date = date;
}
public void setFieldEngineer(String fieldEngineer) {
this.fieldEngineer = fieldEngineer;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public void setIrNo(Integer irNo) {
this.irNo = irNo;
}
public void setJoNo(Integer joNo) {
this.joNo = joNo;
}
public void setAddress(String address) {
this.address = address;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public void setEmail(String email) {
this.email = email;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public void setTimeOut(String timeOut) {
this.timeOut = timeOut;
}
public void setProductType(String productType) {
this.productType = productType;
}
public void setProblem(String problem) {
this.problem = problem;
}
}
Make your POJO class like this
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("srNo")
#Expose
private Integer srNo;
#SerializedName("date")
#Expose
private String date;
#SerializedName("fieldEngineer")
#Expose
private String fieldEngineer;
#SerializedName("accountName")
#Expose
private String accountName;
#SerializedName("irNo")
#Expose
private Integer irNo;
#SerializedName("joNo")
#Expose
private Integer joNo;
#SerializedName("address")
#Expose
private String address;
#SerializedName("contactPerson")
#Expose
private String contactPerson;
#SerializedName("designation")
#Expose
private String designation;
#SerializedName("contactNo")
#Expose
private String contactNo;
#SerializedName("email")
#Expose
private String email;
#SerializedName("timeIn")
#Expose
private String timeIn;
#SerializedName("timeOut")
#Expose
private String timeOut;
#SerializedName("productType")
#Expose
private String productType;
#SerializedName("problem")
#Expose
private String problem;
public Integer getSrNo() {
return srNo;
}
public void setSrNo(Integer srNo) {
this.srNo = srNo;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getFieldEngineer() {
return fieldEngineer;
}
public void setFieldEngineer(String fieldEngineer) {
this.fieldEngineer = fieldEngineer;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Integer getIrNo() {
return irNo;
}
public void setIrNo(Integer irNo) {
this.irNo = irNo;
}
public Integer getJoNo() {
return joNo;
}
public void setJoNo(Integer joNo) {
this.joNo = joNo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactPerson() {
return contactPerson;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTimeIn() {
return timeIn;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public String getTimeOut() {
return timeOut;
}
public void setTimeOut(String timeOut) {
this.timeOut = timeOut;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getProblem() {
return problem;
}
public void setProblem(String problem) {
this.problem = problem;
}
}
make sure to have Gson Converter in your retrofit instance
private static Retrofit getRetrofitInstance() {
return new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
then make call and put the data in ArrayList
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.android.ras.ResObj.getSrNo()' on a null object reference
Note: NullPointerException because you did not declare SrNo inside the model class
Try to use a jason to java class generator:
http://www.jsonschema2pojo.org/
Source type: JSON
Annotation style: Gson( if you used GSON) or none
Include getters and setters
public class Example {
private Integer srNo;
private String date;
private String fieldEngineer;
private String accountName;
private Integer irNo;
private Integer joNo;
private String address;
private String contactPerson;
private String designation;
private String contactNo;
private String email;
private String timeIn;
private String timeOut;
private String productType;
private String problem;
public Integer getSrNo() {
return srNo;
}
public void setSrNo(Integer srNo) {
this.srNo = srNo;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getFieldEngineer() {
return fieldEngineer;
}
public void setFieldEngineer(String fieldEngineer) {
this.fieldEngineer = fieldEngineer;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Integer getIrNo() {
return irNo;
}
public void setIrNo(Integer irNo) {
this.irNo = irNo;
}
public Integer getJoNo() {
return joNo;
}
public void setJoNo(Integer joNo) {
this.joNo = joNo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactPerson() {
return contactPerson;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTimeIn() {
return timeIn;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public String getTimeOut() {
return timeOut;
}
public void setTimeOut(String timeOut) {
this.timeOut = timeOut;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getProblem() {
return problem;
}
public void setProblem(String problem) {
this.problem = problem;
}
}
first : Check response output,
you can Log.i or Toast it,,,
If your response not load or null ... - (the Problem in here)
Second : if respon Ok, Check your ResObj.getSrNo().
Print again... check
String srNo = resObj.getSrNo();
Log.i srNo... (problem or not)
Or checkyour Class Codebeautify
JsonObject paramObject = new JsonObject();
Call<ResObj> call = userService.userLogin(paramObject); // paramObject is empty object
You are passing empty JsonObject to your API parameter.
So you have to add parameter value to your paramObject. like this
try {
JsonObject paramObject = new JsonObject();
paramObject.addProperty("mobile", mobile);
// add other properties if you have
} catch (JSONException e) {
e.printStackTrace();
}
after that you should call your api like
Call<ResObj> call = userService.userLogin(paramObject);
As i am seeing the problem is in parsing, The retrofit can not mapping as your response is n't having ResObj as root.
{ "ResObj": { "srNo": 1, "date": "11/14/201912: 00: 00AM", "fieldEngineer": "Angel", "accountName": "Forever21Megamall", "irNo": 1, "joNo": 1, "address": "MandaluyongCity", "contactPerson": "JansenBabon", "designation": "", "contactNo": "", "email": "", "timeIn": "00: 00: 00", "timeOut": "00: 00: 00", "productType": "Security", "problem": "" } }
Modify your response or change your request
Call<JSONObject> call = userService.userLogin(paramObject);
Later in extract the values manually.
I am consuming an API about cryptocurrency news called CryptoCompare.
My problem is that I can't detect what my code error is.
The error is as follows -> com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 70 path $.Data
I copy the Json and my two classes to help me find the solution.
Json:
{
"Type": 100,
"Message": "News list successfully returned",
"Promoted": [
],
"Data": [
{
"id": "2940487",
"guid": "https://cointelegraph.com/news/australian-hacker-pleads-guilty-to-stealing-450-000-in-xrp-last-year",
"published_on": 1566590880,
"imageurl": "https://images.cryptocompare.com/news/cointelegraph/dj0O90McM86.png",
"title": "Australian Hacker Pleads Guilty to Stealing $450,000 in XRP Last Year",
"url": "https://cointelegraph.com/news/australian-hacker-pleads-guilty-to-stealing-450-000-in-xrp-last-year",
"source": "cointelegraph",
"body": "An Australian woman has pleaded guilty to stealing $450,000 in XRP",
"tags": "Altcoin|Australia|Fraud|Hackers|XRP|Tokens|Police",
"categories": "XRP|ICO|Altcoin",
"upvotes": "0",
"downvotes": "0",
"lang": "EN",
"source_info": {
"name": "CoinTelegraph",
"lang": "EN",
"img": "https://images.cryptocompare.com/news/default/cointelegraph.png"
}
},
]
Link of Api -> https://min-api.cryptocompare.com/data/v2/news/?lang=EN
Java Class News:
public class News {
#SerializedName("Type")
#Expose
private Integer type;
#SerializedName("Message")
#Expose
private String message;
#SerializedName("Data")
#Expose
private List<Article> articles = null;
#SerializedName("HasWarning")
#Expose
private Boolean hasWarning;
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
}
public Boolean getHasWarning() {
return hasWarning;
}
public void setHasWarning(Boolean hasWarning) {
this.hasWarning = hasWarning;
}
Java Class Article:
public class Article {
#SerializedName("id")
#Expose
private String id;
#SerializedName("guid")
#Expose
private String guid;
#SerializedName("published_on")
#Expose
private Integer publishedOn;
#SerializedName("imageurl")
#Expose
private String imageurl;
#SerializedName("title")
#Expose
private String title;
#SerializedName("url")
#Expose
private String url;
#SerializedName("source")
#Expose
private String source;
#SerializedName("body")
#Expose
private String body;
#SerializedName("tags")
#Expose
private String tags;
#SerializedName("categories")
#Expose
private String categories;
#SerializedName("upvotes")
#Expose
private String upvotes;
#SerializedName("downvotes")
#Expose
private String downvotes;
#SerializedName("lang")
#Expose
private String lang;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public Integer getPublishedOn() {
return publishedOn;
}
public void setPublishedOn(Integer publishedOn) {
this.publishedOn = publishedOn;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
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 getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getCategories() {
return categories;
}
public void setCategories(String categories) {
this.categories = categories;
}
public String getUpvotes() {
return upvotes;
}
public void setUpvotes(String upvotes) {
this.upvotes = upvotes;
}
public String getDownvotes() {
return downvotes;
}
public void setDownvotes(String downvotes) {
this.downvotes = downvotes;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
}
Interface to call Api:
public interface ApiInterface {
#GET("news")
Call<News> getNews(
#Query("lang") String lang,
#Query("api_key") String apiKey,
#Query("lTs") int lTs
);
Retrofit Class Builder
public static Retrofit getApiClient(String BASE_URL){
retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.client(getUnsafeOkHttpClient().build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
Fragment of Code when i call the api
private void LoadJson(){
swipeRefreshLayout.setRefreshing(true);
final ApiInterface apiInterface = ApiClient.getApiClient(ApiUtils.BASE_URL_NEWS).create(ApiInterface.class);
Call<News> call;
call = apiInterface.getNews("EN", ApiUtils.API_KEY,0);
call.enqueue(new Callback<News>() {
#Override
public void onResponse(Call<News> call, Response<News> response) {
if (response.isSuccessful() && response.body() != null){
articles.addAll(response.body().getArticles());
if (articles.size() - response.body().getArticles().size() == 0){
adapterNews.notifyDataSetChanged();
} else {
adapterNews.notifyItemRangeInserted(articles.size() - response.body().getArticles().size(), response.body().getArticles().size());
}
swipeRefreshLayout.setRefreshing(false);
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(getContext(), "No result", Toast.LENGTH_SHORT).show();
swipeRefreshLayout.setRefreshing(false);
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<News> call, Throwable t) {
Log.e(TAG, "ERROR API: " + t.getMessage() + " - " + t.getCause());
}
});
}
Any contribution is very helpful.
Thank you
FIXED THE PROBLEM WAS IN THE CALL
I notice that when you try query on api with wrong value like this
https://min-api.cryptocompare.com/data/v2/news/?lang=en
gives you json instead of array for data so this produce error
For fix and test instead of Locale.getDefault().getLanguage() use just "EN" and check the result
also for more help you can use this logging-interceptor
There is JSON file and i want get through POJO so i Created POJO file as well but at customer data it show in some error like i mention in title i don't know what's happening i mean my whole team don't why it's happening.
I've try everything which i would try but nothing is helping me out
{
"Success": true,
"Message": "Device Not Found",
"Customer_Data": [{
"customerid": 12365,
"customername": "Mukesh SHARMA",
"gender": "M",
"personalcontact": 999999999,
"homecontact": 999999999,
"emailid": "mukeshr334#gmail.com",
"address": "RockStar",
"designation": "Chief Life Insurance Advisor",
"stateid": 22,
"statename": "Uttar Pradesh",
"cityid": 557,
"cityname": "Sant Ravidas Nagar",
"pincode": 221304,
"birthdate": "14-11-1983",
"marriagedate": "2018-01-01",
"category": "-- Select --",
"mdrttick": false,
"profilepicture": "http://mdddddddtaupdate.in/profile_pic/12365.jpg",
"branchname": "ModelTown",
"branchcode": "123",
"licbranchid": 20596,
"division": "Delhi DO-II",
"licdivisionentryid": 51,
"password": "123456",
"employeename": "Shahnawaz Khan",
"empcontact": 999999999,
"empmail": "shane_madddian#yahoo.com",
"dealername": "Sachinder",
"deacontact": 999999999,
"deamail": "ddd#gamil.com",
"club_member": "-- Select --",
"lifeinsurance": false,
"nonlife": false,
"healthinsurance": false,
"mutualfunds": false,
"other": false,
"efrom": "A",
"edate": "2019-05-09 13:03:17.63214",
"website": "",
"maxdate": "01-01-2000 00:00:00"
}],
"Customer_Device": "",
"Customer_Event": "",
"All_Event": [{
"event_id": 6,
"event_name": "Test Event - 1",
"start_date": "01/06/2019",
"end_date": "02/06/2019",
"address_1": "Mumbai",
"address_2": "Mumbai",
"location_link": "https://goo.gl/maps/vTia6DQxwmiA5kvz6",
"pincode": 400060,
"state_id": 10,
"city_id": 355,
"sechudel": "Test",
"itinerary": "Test",
"edate": "2019-05-09T17:00:05.95592",
"eventimg": "http://zaidicorp.in/login/ProcessImage/636935218388448729.png"
}],
"Status": 2,
"Currentdate": "5/18/2019"
}
This is my POJO
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
public class OtpCheck implements Serializable {
#SerializedName("Success")
#Expose
private Boolean success;
#SerializedName("Message")
#Expose
private String message;
#SerializedName("Customer_Data")
#Expose
private List<CustomerData> customerData = null;
#SerializedName("Customer_Device")
#Expose
private String customerDevice;
#SerializedName("Customer_Event")
#Expose
private String customerEvent;
#SerializedName("All_Event")
#Expose
private List<EventDetail> getEventDetails = null;
#SerializedName("Status")
#Expose
private Integer status;
#SerializedName("Currentdate")
#Expose
private String currentdate;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<CustomerData> getCustomerData() {
return customerData;
}
public void setCustomerData(List<CustomerData> customerData) {
this.customerData = customerData;
}
public String getCustomerDevice() {
return customerDevice;
}
public void setCustomerDevice(String customerDevice) {
this.customerDevice = customerDevice;
}
public String getCustomerEvent() {
return customerEvent;
}
public void setCustomerEvent(String customerEvent) {
this.customerEvent = customerEvent;
}
public List<EventDetail> getEventDetails() {
return getEventDetails;
}
public void setEventDetails(List<EventDetail> getEventDetails) {
this.getEventDetails = getEventDetails;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCurrentdate() {
return currentdate;
}
public void setCurrentdate(String currentdate) {
this.currentdate = currentdate;
}
public static class EventDetail implements Serializable {
#SerializedName("event_id")
#Expose
private Integer eventId;
#SerializedName("event_name")
#Expose
private String eventName;
#SerializedName("start_date")
#Expose
private String startDate;
#SerializedName("end_date")
#Expose
private String endDate;
#SerializedName("address_1")
#Expose
private String address1;
#SerializedName("address_2")
#Expose
private String address2;
#SerializedName("location_link")
#Expose
private String locationLink;
#SerializedName("pincode")
#Expose
private Integer pincode;
#SerializedName("state_id")
#Expose
private Integer stateId;
#SerializedName("city_id")
#Expose
private Integer cityId;
#SerializedName("sechudel")
#Expose
private String sechudel;
#SerializedName("itinerary")
#Expose
private String itinerary;
#SerializedName("edate")
#Expose
private String edate;
#SerializedName("eventimg")
#Expose
private String eventimg;
public Integer getEventId() {
return eventId;
}
public void setEventId(Integer eventId) {
this.eventId = eventId;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getLocationLink() {
return locationLink;
}
public void setLocationLink(String locationLink) {
this.locationLink = locationLink;
}
public Integer getPincode() {
return pincode;
}
public void setPincode(Integer pincode) {
this.pincode = pincode;
}
public Integer getStateId() {
return stateId;
}
public void setStateId(Integer stateId) {
this.stateId = stateId;
}
public Integer getCityId() {
return cityId;
}
public void setCityId(Integer cityId) {
this.cityId = cityId;
}
public String getSechudel() {
return sechudel;
}
public void setSechudel(String sechudel) {
this.sechudel = sechudel;
}
public String getItinerary() {
return itinerary;
}
public void setItinerary(String itinerary) {
this.itinerary = itinerary;
}
public String getEdate() {
return edate;
}
public void setEdate(String edate) {
this.edate = edate;
}
public String getEventimg() {
return eventimg;
}
public void setEventimg(String eventimg) {
this.eventimg = eventimg;
}
}
public static class CustomerData implements Serializable {
#SerializedName("customerid")
#Expose
private Integer customerid;
#SerializedName("customername")
#Expose
private String customername;
#SerializedName("gender")
#Expose
private String gender;
#SerializedName("personalcontact")
#Expose
private Integer personalcontact;
#SerializedName("homecontact")
#Expose
private Integer homecontact;
#SerializedName("emailid")
#Expose
private String emailid;
#SerializedName("address")
#Expose
private String address;
#SerializedName("designation")
#Expose
private String designation;
#SerializedName("stateid")
#Expose
private Integer stateid;
#SerializedName("statename")
#Expose
private String statename;
#SerializedName("cityid")
#Expose
private Integer cityid;
#SerializedName("cityname")
#Expose
private String cityname;
#SerializedName("pincode")
#Expose
private Integer pincode;
#SerializedName("birthdate")
#Expose
private String birthdate;
#SerializedName("marriagedate")
#Expose
private String marriagedate;
#SerializedName("category")
#Expose
private String category;
#SerializedName("mdrttick")
#Expose
private Boolean mdrttick;
#SerializedName("profilepicture")
#Expose
private String profilepicture;
#SerializedName("branchname")
#Expose
private String branchname;
#SerializedName("branchcode")
#Expose
private String branchcode;
#SerializedName("licbranchid")
#Expose
private Integer licbranchid;
#SerializedName("division")
#Expose
private String division;
#SerializedName("licdivisionentryid")
#Expose
private Integer licdivisionentryid;
#SerializedName("password")
#Expose
private String password;
#SerializedName("employeename")
#Expose
private String employeename;
#SerializedName("empcontact")
#Expose
private Integer empcontact;
#SerializedName("empmail")
#Expose
private String empmail;
#SerializedName("dealername")
#Expose
private String dealername;
#SerializedName("deacontact")
#Expose
private Integer deacontact;
#SerializedName("deamail")
#Expose
private String deamail;
#SerializedName("club_member")
#Expose
private String clubMember;
#SerializedName("lifeinsurance")
#Expose
private Boolean lifeinsurance;
#SerializedName("nonlife")
#Expose
private Boolean nonlife;
#SerializedName("healthinsurance")
#Expose
private Boolean healthinsurance;
#SerializedName("mutualfunds")
#Expose
private Boolean mutualfunds;
#SerializedName("other")
#Expose
private Boolean other;
#SerializedName("efrom")
#Expose
private String efrom;
#SerializedName("edate")
#Expose
private String edate;
#SerializedName("website")
#Expose
private String website;
#SerializedName("maxdate")
#Expose
private String maxdate;
public Integer getCustomerid() {
return customerid;
}
public void setCustomerid(Integer customerid) {
this.customerid = customerid;
}
public String getCustomername() {
return customername;
}
public void setCustomername(String customername) {
this.customername = customername;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getPersonalcontact() {
return personalcontact;
}
public void setPersonalcontact(Integer personalcontact) {
this.personalcontact = personalcontact;
}
public Integer getHomecontact() {
return homecontact;
}
public void setHomecontact(Integer homecontact) {
this.homecontact = homecontact;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public Integer getStateid() {
return stateid;
}
public void setStateid(Integer stateid) {
this.stateid = stateid;
}
public String getStatename() {
return statename;
}
public void setStatename(String statename) {
this.statename = statename;
}
public Integer getCityid() {
return cityid;
}
public void setCityid(Integer cityid) {
this.cityid = cityid;
}
public String getCityname() {
return cityname;
}
public void setCityname(String cityname) {
this.cityname = cityname;
}
public Integer getPincode() {
return pincode;
}
public void setPincode(Integer pincode) {
this.pincode = pincode;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getMarriagedate() {
return marriagedate;
}
public void setMarriagedate(String marriagedate) {
this.marriagedate = marriagedate;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Boolean getMdrttick() {
return mdrttick;
}
public void setMdrttick(Boolean mdrttick) {
this.mdrttick = mdrttick;
}
public String getProfilepicture() {
return profilepicture;
}
public void setProfilepicture(String profilepicture) {
this.profilepicture = profilepicture;
}
public String getBranchname() {
return branchname;
}
public void setBranchname(String branchname) {
this.branchname = branchname;
}
public String getBranchcode() {
return branchcode;
}
public void setBranchcode(String branchcode) {
this.branchcode = branchcode;
}
public Integer getLicbranchid() {
return licbranchid;
}
public void setLicbranchid(Integer licbranchid) {
this.licbranchid = licbranchid;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public Integer getLicdivisionentryid() {
return licdivisionentryid;
}
public void setLicdivisionentryid(Integer licdivisionentryid) {
this.licdivisionentryid = licdivisionentryid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmployeename() {
return employeename;
}
public void setEmployeename(String employeename) {
this.employeename = employeename;
}
public Integer getEmpcontact() {
return empcontact;
}
public void setEmpcontact(Integer empcontact) {
this.empcontact = empcontact;
}
public String getEmpmail() {
return empmail;
}
public void setEmpmail(String empmail) {
this.empmail = empmail;
}
public String getDealername() {
return dealername;
}
public void setDealername(String dealername) {
this.dealername = dealername;
}
public Integer getDeacontact() {
return deacontact;
}
public void setDeacontact(Integer deacontact) {
this.deacontact = deacontact;
}
public String getDeamail() {
return deamail;
}
public void setDeamail(String deamail) {
this.deamail = deamail;
}
public String getClubMember() {
return clubMember;
}
public void setClubMember(String clubMember) {
this.clubMember = clubMember;
}
public Boolean getLifeinsurance() {
return lifeinsurance;
}
public void setLifeinsurance(Boolean lifeinsurance) {
this.lifeinsurance = lifeinsurance;
}
public Boolean getNonlife() {
return nonlife;
}
public void setNonlife(Boolean nonlife) {
this.nonlife = nonlife;
}
public Boolean getHealthinsurance() {
return healthinsurance;
}
public void setHealthinsurance(Boolean healthinsurance) {
this.healthinsurance = healthinsurance;
}
public Boolean getMutualfunds() {
return mutualfunds;
}
public void setMutualfunds(Boolean mutualfunds) {
this.mutualfunds = mutualfunds;
}
public Boolean getOther() {
return other;
}
public void setOther(Boolean other) {
this.other = other;
}
public String getEfrom() {
return efrom;
}
public void setEfrom(String efrom) {
this.efrom = efrom;
}
public String getEdate() {
return edate;
}
public void setEdate(String edate) {
this.edate = edate;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getMaxdate() {
return maxdate;
}
public void setMaxdate(String maxdate) {
this.maxdate = maxdate;
}
}
}
Expected BEGIN_ARRAY but was String at line 1 column 61 . $ customer.Data
Customer_Event is Arraylist
#SerializedName("Customer_Event")
#Expose
private List<CustomerEvent> customerEvent = null;
Gson Library expecting the Array first not the Object. there is nothing wrong in your code. but need to modify the JSON Structure here.
Try using this structure :
Note rootArray is starting point/ is used for your reference
rootArray[
// object
{
"Key": value,
"Key": value,
"Key": value
}
// array1
"Customer_Data":[
{
"Key": value,
"Key": value,
"Key": value
}
],
// array 2
"All_Event": [
{
"Key": value,
"Key": value,
"Key": value
}
]
]
Iam trying t get values from a HashMap but when i call him and setText the value i always get Null, let me show the code:
MyValues.class
private List<ItemsBean> items;
public List<ItemsBean> getItems() { return items;}
public void setItems(List<ItemsBean> items) { this.items = items; }
public static class ItemsBean {
private Map<String, leakBean> Gitt;
public Map<String, leakBean> getGitt() { return Gitt;}
public void setGitt(Map<String, leakBean> Gitt) { this.Gitt = Gitt;}
public static class leakBean {
private int id;
private String dev;
public int getId() {return id; }
public String getDev(){return dev;}
public void setId(int id) { this.id = id;}
public void setDev(String dev){this.dev = dev;}
}
I´m using Gson so for get the values and use it for .setText or Toast im trying to access like this:
MyValues object;
txt1.setText(String.valueOf( object.getItems().get(0).getGitt().get("id")));
Here i get null, can someone helpme with this? i just need to access to values, also the items.size(); return 1 and must return 3
here is hte JSON:
{
"id": 1001,
"name": "Super1",
"user": {
"name": "The Super 1"
},
"items": [
{
"987987M7812b163eryrt": {
"id": 1,
"dev": "seed"
},
"90812bn120893juuh": {
"id": 2,
"dev": "none"
},
"981273jn19203nj123rg": {
"id": 3,
"dev": "mine"
}
}
]}
Try with these POJOs:
MyValues.java
public class MyValues {
private int id;
private String name;
private User user;
private List<HashMap<String, ItemsBean>> items;
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 User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<HashMap<String, ItemsBean>> getItems() {
return items;
}
public void setItems(List<HashMap<String, ItemsBean>> items) {
this.items = items;
}
}
User.java
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ItemsBean.java
public class ItemsBean {
private int id;
private String dev;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDev() {
return dev;
}
public void setDev(String dev) {
this.dev = dev;
}
}
You can no access the values like so:
object.getItems().get(0).get("987987M7812b163eryrt").getId();
I retrieve a JSON result from an API :
[{
"oid": "axd7wtlk6xd2fbwlc5wk",
"id": "aazzzza",
"name": "aazzaa",
"logo": {
"type": 0,
"data": "iVB.............5CYII="
},
"timestamp": 1438608571013,
"email": "contact#azzaa.net",
"modified": "test",
"url": "http://www.azzaa.net"
},
{
"oid": "quj3dzygfwygl5uxsbxk",
"name": "KZZZ",
"modified": "test",
"timestamp": 1438854099511,
"id": "kess"
},...]
but when I try to map to a customer object I get the error Expected a string but was BEGIN_OBJECT :
response = webService.RequestGet(url, header);
result = null;
try {
result = new JSONArray(response);
Utils.LogWarning(response);
} catch (JSONException e) {
Utils.LogError("Could not load json response", e);
}
Type customerType = new TypeToken<Collection<Customer>>() {
}.getType();
ArrayList<Customer> alCustomers = null;
alCustomers = new Gson().fromJson(result.toString(), customerType);
Here is my Customer class :
public class Customer implements Serializable {
private String id = "";
private String name = "";
private String email = "";
private String url = "";
private String address = "";
private String stamp = "";
//private transient String logo = "";
private long timestamp = 0L;
private String modified = "";
...
}
I have been through a lot of answers regarding this problem that I have also for other types of objects, but I can't find a working solution.
Create a modal with the values of JSON result like
public class Customer {
private String oid;
private String id;
private String name;
private String timestamp;
private String email;
private String modified;
private String url;
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
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 getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Logo getLogo() {
return logo;
}
public void setLogo(Logo logo) {
this.logo = logo;
}
private Logo logo;
}
public class Logo {
private int type;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
private String data;
}
Gson gson = new Gson();
Type listType = new TypeToken<List<Customer>>(){}.getType();
List<Customer> customer= (List<Customer>) gson.fromJson(jsonOutput, listType);