Passing array problem in retrofit post request - java

I have face a problem retrofit library in android java.
here is the json Body
{
"title":"Android ",
"type":"project",
"category_id":"1",
"tags":["swift","java","android"],
"end_date":"2021-9-30",
"description":"testing",
"budget":"500"
}
This the pojo class
public class draftedJobPostModel {
private String title;
private String type;
private int category_id;
ArrayList<String> tags;
private String end_date;
private String description;
private int budget;
private String post_type;
public draftedJobPostModel() {
}
public draftedJobPostModel(String title, String type, int category_id, ArrayList<String> tags, String end_date, String description, int budget, String post_type) {
this.title = title;
this.type = type;
this.category_id = category_id;
this.tags = tags;
this.end_date = end_date;
this.description = description;
this.budget = budget;
this.post_type = post_type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getCategory_id() {
return category_id;
}
public void setCategory_id(int category_id) {
this.category_id = category_id;
}
public ArrayList<String> getTags() {
return tags;
}
public void setTags(ArrayList<String> tags) {
this.tags = tags;
}
public String getEnd_date() {
return end_date;
}
public void setEnd_date(String end_date) {
this.end_date = end_date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getBudget() {
return budget;
}
public void setBudget(int budget) {
this.budget = budget;
}
public String getPost_type() {
return post_type;
}
public void setPost_type(String post_type) {
this.post_type = post_type;
}
}
Add value from chip:
ArrayList<String> arrayTags = new ArrayList<>();
for (int i=0;i<chipGroup.getChildCount();i++)
{
Chip chip = (Chip) chipGroup.getChildAt(i);
arrayTags.add(chip.getText().toString());
}
retrofit call method:
Service service = Client.retrofit.create(Service.class);
Call<createJobPostModel> call = service.createJob("Bearer"+" "+token,title,jobtype,fieldId, arrayTags,date,budget,description);
call.enqueue(new Callback<createJobPostModel>() {
#Override
public void onResponse(Call<createJobPostModel> call, Response<createJobPostModel> response) {
if (response.isSuccessful()){
/* Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();*/
Toast.makeText(getActivity(),arrayTags.toString(), Toast.LENGTH_LONG).show();
/*arrayTags.clear();*/
}else{
Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<createJobPostModel> call, Throwable t) {
Toast.makeText(getActivity(), "Failed", Toast.LENGTH_SHORT).show();
}
});
Everything is ok but when i pass the arraylist its shows only last index of array value in database.
here is the return value:
"tags": "Android",
but i want this:
"tags": [
"swift",
"IOS",
"android"
],

Related

How to hande error null body in retrofit?

Im trying to post data with retrofit with jwt bearer authentication, but when i debug response code, its
error 400, and the message is body = null
This is my Intefrace class
#Headers({"accept: text/plain","Content-Type: application/json-patch+json" })
#POST("services/app/ProjectService/Create")
Call<ProjectRequest> postProject(#Header("Authorization") String token,
#Body ProjectRequest projectRequest
);
This is my model class
public class ProjectRequest {
#SerializedName("name")
#Expose
private String name;
#SerializedName("description")
#Expose
private String description;
#SerializedName("ownerId")
#Expose
private int ownerId;
#SerializedName("startPeriod")
#Expose
private String startPeriod;
#SerializedName("endPeriod")
#Expose
private String endPeriod;
#SerializedName("isDraft")
#Expose
private boolean isDraft;
#SerializedName("ownerName")
#Expose
private String ownerName;
#SerializedName("pitId")
#Expose
private int pitId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getOwnerId() {
return ownerId;
}
public void setOwnerId(int ownerId) {
this.ownerId = ownerId;
}
public String getStartPeriod() {
return startPeriod;
}
public void setStartPeriod(String startPeriod) {
this.startPeriod = startPeriod;
}
public String getEndPeriod() {
return endPeriod;
}
public void setEndPeriod(String endPeriod) {
this.endPeriod = endPeriod;
}
public boolean isDraft() {
return isDraft;
}
public void setDraft(boolean draft) {
isDraft = draft;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public int getPitId() {
return pitId;
}
public void setPitId(int pitId) {
this.pitId = pitId;
}
And the main class is
private void initApi() {
projectApi = ApiClient.getClient().create(ProjectApi.class);
}
private void postProject(final boolean isOnline) {
if (isOnline) {
final ProjectRequest projectRequest = new ProjectRequest();
projectRequest.setName(projectName);
projectRequest.setDescription(description);
projectRequest.setOwnerId(1);
projectRequest.setStartPeriod(dateStart);
projectRequest.setEndPeriod(dateEnd);
projectRequest.setDraft(true);
projectRequest.setOwnerName("yogi kun");
projectRequest.setPitId(1);
Call<ProjectRequest> callProject = projectApi.postProject(" Bearer eyJ0eXAiOiJKV1QiLCJub25jZSI6Il and so . . . ",
projectRequest);
callProject.enqueue(new Callback<ProjectRequest>() {
#Override
public void onResponse(#NotNull Call<ProjectRequest> call, #NotNull Response<ProjectRequest> response) {
if (response.isSuccessful()) {
try {
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
String message = "";
if (e.getMessage() != null) {
message = e.getMessage();
}
Toast.makeText(getContext(), "Failed " + message, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getContext(), "Failed " + response, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(#NotNull Call<ProjectRequest> call, #NotNull Throwable t) {
Toast.makeText(getContext(), "Failure" + t, Toast.LENGTH_SHORT).show();
}
});
}
And the error is
enter image description here
And
enter image description here
Might be an issue with how the JSON is formatted, compared to what you're expecting. Are you able to use something like Postman and try this API call to see the format it comes back? Can't tell that much but the error message shown is finding some array somewhere in the JSON

How to display JSON data from API server in TextView and EditText in Android?

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.

GSON: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

While working on retrofit, I used http://www.jsonschema2pojo.org this site to convert json to POJO. But I got an error while parsing JSON like this. Its saying Expected BEGIN_OBJECT but was BEGIN_ARRAY.
[
{
"uuid": "12e26270-b506-11e9-ad81-5f542bb63d66",
"first_name": "Nohar",
"last_name": "Kumar",
"title": "Premier League Player",
"gender": "N/A",
"date_of_birth": null,
"relationship_status": null,
"fav_quote": null,
"best_achievement": null,
"experience": null,
"skills": null,
"height": null,
"weight": null,
"about": null
}
]
Here is my modal class used for json to POJO.
public class UserAboutModel {
#SerializedName("uuid")
#Expose
private String uuid;
#SerializedName("first_name")
#Expose
private String firstName;
#SerializedName("last_name")
#Expose
private String lastName;
#SerializedName("title")
#Expose
private String title;
#SerializedName("gender")
#Expose
private String gender;
#SerializedName("date_of_birth")
#Expose
private String dateOfBirth;
#SerializedName("relationship_status")
#Expose
private String relationshipStatus;
#SerializedName("fav_quote")
#Expose
private String favQuote;
#SerializedName("best_achievement")
#Expose
private String bestAchievement;
#SerializedName("experience")
#Expose
private String experience;
#SerializedName("skills")
#Expose
private String skills;
#SerializedName("about")
#Expose
private String about;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getRelationshipStatus() {
return relationshipStatus;
}
public void setRelationshipStatus(String relationshipStatus) {
this.relationshipStatus = relationshipStatus;
}
public String getFavQuote() {
return favQuote;
}
public void setFavQuote(String favQuote) {
this.favQuote = favQuote;
}
public String getBestAchievement() {
return bestAchievement;
}
public void setBestAchievement(String bestAchievement) {
this.bestAchievement = bestAchievement;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getSkills() {
return skills;
}
public void setSkills(String skills) {
this.skills = skills;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
}
Here I am calling the method to get the response.
private void getUserAbout() {
apiInterface = APIClient.getClient().create(ApiInterface.class);
SharedPreferences sp = getSharedPreferences("UserData", Context.MODE_PRIVATE);
String token = sp.getString("User_Token", "");
Log.v("working", "working");
Call<UserAboutModel> call = apiInterface.userAboutBasic(currentUserUuid, "Bearer " + token);
call.enqueue(new Callback<UserAboutModel>() {
#Override
public void onResponse(Call<UserAboutModel> call, Response<UserAboutModel> response) {
if (response.isSuccessful()) {
String name = response.body().getFirstName() + " " + response.body().getLastName();
SharedPreferences pref = getSharedPreferences("UserAbout", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
Log.v("NAme", name);
Log.v("Title", response.body().getTitle());
editor.putString("UserName", name);
editor.putString("UserTitle", response.body().getTitle());
editor.putString("UserDOB", response.body().getDateOfBirth());
editor.putString("UserFAvQuote", response.body().getFavQuote());
editor.putString("UserSkill", response.body().getSkills());
editor.putString("UserGender", response.body().getGender());
editor.putString("UserRelationshipStatus", response.body().getRelationshipStatus());
editor.putString("UserExperience", response.body().getExperience());
editor.putString("UserBestAchievment", response.body().getBestAchievement());
editor.putString("UserCategory", primarySports.getText().toString());
editor.putString("UserSports", response.body().getExperience());
editor.apply();
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getApplicationContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<UserAboutModel> call, Throwable t) {
call.cancel();
Log.d("TAG", t.toString());
}
});
}
And here is the log details
D/OkHttp: [{"uuid":"12e26270-b506-11e9-ad81-5f542bb63d66","first_name":"Nohar","last_name":"Kumar","title":"Premier League Player","gender":"N\/A","date_of_birth":null,"relationship_status":null,"fav_quote":null,"best_achievement":null,"experience":null,"skills":null,"height":null,"weight":null,"about":null}]
D/TAG: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
Can anyone help me out? How to solve this error?
The response that you are getting from the server is a list of UserAboutModel. However, in your code, you are expecting a single data. I think the function should look like the following.
public void onResponse(Call<UserAboutModel> call, Response<List<UserAboutModel>> response) {
// Now take the first element from the response list
// and then do the rest of your work
}
Instead of Response<UserAboutModel> use a Response<List<UserAboutModel>> so that it tells the function to expect a list of UserAboutModel.
Hope that helps!

Json error for Java with Gson and retrofit [Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 70 path $.Data]

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

Deserialization got null String should have value

I got a quite weird problem, forgive me if it became an attention problem, but I'm running on coffee right now!
I have this Json:
[
{
"address":"RS 239, Km 18,2 nÂș 4631 - Novo Hamburgo",
"closingTime":"06:00",
"description":"Curta como quiser.",
"distance":"6,328.35 km",
"iconUrl":"~\/Images\/Establishment\/Bar Alternativo.png",
"idEstablishment":5,
"name":"Bar Alternativo",
"openingTime":"22:30",
"phone":"(51) 3778-1820",
"type":"Casa Noturna \/ Balada"
}
]
And when I try deserialize this one using this code:
public static ArrayList<Establishment> serializeEstablishmentList(String json) {
ObjectMapper mapper = new ObjectMapper();
ArrayList<Establishment> establishments = null;
try {
establishments = mapper.readValue(json, new TypeReference<List<Establishment>>(){});
} catch (IOException e) {
e.printStackTrace();
}
return establishments;
}
My distance property do not get its value, image from debugger:
here goes my Establishment class:
public class Establishment {
private long idEstablishment;
private Drawable icon;
private String iconUrl;
private String name;
private String type;
private boolean workingStatus;
private String openingTime;
private String closingTime;
private String distance;
private String phone;
private String description;
private String address;
public Establishment() {
}
public Establishment(long idEstablishment, Drawable icon, String iconUrl, String name, String type, boolean workingStatus, String openingTime, String closingTime, String distance, String phone, String description, String address) {
this.idEstablishment = idEstablishment;
this.icon = icon;
this.iconUrl = iconUrl;
this.name = name;
this.type = type;
this.workingStatus = workingStatus;
this.openingTime = openingTime;
this.closingTime = closingTime;
this.distance = distance;
this.phone = phone;
this.description = description;
this.address = address;
}
public Establishment(long id, Drawable icon, String name, boolean workingStatus, String openingTime,
String closingTime, String distance) {
this.idEstablishment = id;
this.icon = icon;
this.name = name;
this.workingStatus = workingStatus;
this.openingTime = openingTime;
this.closingTime = closingTime;
this.distance = distance;
}
public long getIdEstablishment() {
return idEstablishment;
}
public void setIdEstablishment(long idEstablishment) {
this.idEstablishment = idEstablishment;
}
public Drawable getIcon() {
return icon;
}
public void setIcon(Drawable icon) {
this.icon = icon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean getWorkingStatus() {
return workingStatus;
}
public String getWorkingStatusLabel(){
return workingStatus ? "Aberto" : "Fechado";
}
public void setWorkingStatus(boolean workingStatus) {
this.workingStatus = workingStatus;
}
public String getOpeningTime() {
return openingTime;
}
public void setOpeningTime(String openingTime) {
this.openingTime = openingTime;
}
public String getClosingTime() {
return closingTime;
}
public void setClosingTime(String closingTime) {
this.closingTime = closingTime;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = this.distance;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isWorkingStatus() {
return workingStatus;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Any idea?
Your setter method is wrong:
public void setDistance(String distance) {
this.distance = this.distance;
}
This should be:
public void setDistance(String distance) {
this.distance = distance;
}

Categories