I want to parse a Gson information but getting errors - java

I am trying to send the data of source and destination.
public void sendPost(final SearchSendModel searchSendModel){
//public void sendPost( String source, String destination){
Call call = mAPIService.sendSearch(searchSendModel);
//Call call = mAPIService.sendSearch(source, destination);
call.enqueue(new Callback<SearchModel>() {
#Override
public void onResponse(Call<SearchModel> call, Response<SearchModel> response) {
Toast.makeText(Search.this, " Responce " +response.body(), Toast.LENGTH_SHORT).show();
Log.v("Responce", "Responce "+response.body());
if (response.isSuccessful()){
SearchModel searchResponse = response.body();
assert searchResponse != null;
String content = "";
content += "Code: " +response.code() +"\n";
content += "vech_id: " + searchResponse.getVechId() +"\n";
content += "model_no: " + searchResponse.getModelNo() +"\n";
content += "reg_no: " +searchResponse.getRegNo() +"\n";
content += "delivery_start_date: " +searchResponse.getDeliveryStartDate() +"\n";
content += "delivery_end_date: " +searchResponse.getDeliveryEndDate() +"\n";
content += "full_percent: " +searchResponse.getFullPercent() +"\n";
content += "approval_status: " +searchResponse.getApprovalStatus() +"\n";
content +="source: " +searchResponse.getSource() +"\n";
content += "destination: " +searchResponse.getDestination() +"\n\n";
Toast.makeText(getApplicationContext(),content,Toast.LENGTH_LONG).show();
searchModelList.add(searchResponse);
}else {
Toast.makeText(getApplicationContext(),"Something is error",Toast.LENGTH_SHORT).show();
}
This is the Json response which i am expecting:
[
{
"vech_id": "30",
"model_no": "8956",
"reg_no": "98765",
"delivery_start_date": "2020-03-18",
"delivery_end_date": "2020-06-24",
"full_percent": "0.14",
"approval_status": "1",
"source": "ranchi",
"destination": "garwah"
}
]
Interface for API is:
#POST("search_vehicle.php")
#FormUrlEncoded
Call<SearchSendModel> sendSearch(#Body SearchSendModel searchSendModel);
SearchSendModel.java
public class SearchSendModel {
public SearchSendModel(String source, String destination) {
this.source = source;
this.destination = destination;
}
#SerializedName("source")
private String source;
#SerializedName("destination")
private String destination;
public String getSource() {
return source;
}
public String getDestination() {
return destination;
}
}
But I am getting this error always:
java.lang.IllegalStateException:Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 2 column 2 path$

I think your onResponse should use List<SearchModel> instead of SearchModel. Your response format is array.

Related

How To Use Response value In Another Method

I am working on restassured and here is my 2 methods. I want to use the albumId returned from the AlbumList method in the other method
public void AlbumList() {
Response response1 = given().spec(url).queryParam("page", 0).queryParam("size", 100)
.queryParam("sortBy", "createdDate").queryParam("contentType", "album/photo")
.queryParam("sortOrder", "ASC")
.header("Content-type", "application/json")
.header("Accept", "application/json")
.header("X-Auth-Token", payload.userAuth())
.when().get("/album")
.then().assertThat().statusCode(200).extract().response();
Assert.assertEquals(response1.jsonPath().get("[4].label"), "TLOTR");
JsonPath js = new JsonPath(response1.asString());
int count = js.getInt("size()");
// Response check part
for (int i = 0; i < count; i++) {
assertEqual(js, i, "createdDate", AlbumAttributes.actual_createdDate());
assertEqual(js, i, "lastModifiedDate", AlbumAttributes.actual_modifiedDate());
assertEqual(js, i, "uuid", AlbumAttributes.actual_uuid());
if (js.get("[" + i + "].coverPhoto") != null) {
String d = response1.jsonPath().get("[" + i + "].coverPhoto.tempDownloadURL").toString();
Assert.assertTrue(d.matches(AlbumAttributes.actual_temp_url()));
System.out.println(js.get("[" + i + "].coverPhoto.tempDownloadURL").toString() + " is equalent to : " + AlbumAttributes.actual_temp_url());
}
if (js.get("[" + i + "].coverPhoto.metadata['Thumbnail-Large']") != null) {
String e = response1.jsonPath().get("[" + i + "].coverPhoto.metadata['Thumbnail-Large']").toString();
Assert.assertTrue(e.matches(AlbumAttributes.actual_metaData_url()));
System.out.println(js.get("[" + i + "].coverPhoto.metadata['Thumbnail-Large']").toString() + " is equalent to : " + AlbumAttributes.actual_metaData_url());
}
}
String albumId = response1.jsonPath().get("[0].uuid").toString();
String albumId2 = response1.jsonPath().get("[1].uuid").toString();
}
I know these are void and doesnt return anything but idk how to use it. Bye the these methods are in the same class. Thanks in advance
public void AlbumDetails() {
Response response = given().queryParam("page", 0).queryParam("size", 100)
.queryParam("sortBy", "createdDate").queryParam("sortOrder", "DESC")
.header("Content-type", "application/json")
.header("Accept", "application/json")
.header("X-Auth-Token", payload.userAuth())
.when().get("/album/" + albumId)
.then().assertThat().statusCode(200).extract().response();
// Response check part
Assert.assertEquals("[]", response.jsonPath().get("fileList").toString());
Assert.assertEquals("album/photo", response.jsonPath().get("contentType").toString());
Assert.assertEquals("false", response.jsonPath().get("readOnly").toString());
Assert.assertTrue(response.jsonPath().get("createdDate").toString().matches(AlbumAttributes.actual_createdDate()));
Assert.assertTrue(response.jsonPath().get("lastModifiedDate").toString().matches(AlbumAttributes.actual_modifiedDate()));
Assert.assertTrue(response.jsonPath().get("uuid").toString().matches(AlbumAttributes.actual_uuid()));
System.out.println("Album Details Response Test PASS");
long albumDetails_time = response.getTime();
System.out.println("\tAlbum Detail's Api response time is : " + albumDetails_time);
}
The easiest way is to change the return type of the AlbumList() method from void to String:
public String AlbumList() {
And in AlbumDetails() method we should change:
.when().get("/album/" + AlbumList())
Another option is to create instance variable albumId, not locally in AlbumList() method, and use it:
public class SomeClass {
public String albumId;
public void AlbumList() {
...
albumId = response1.jsonPath().get("[0].uuid").toString();
}
public void AlbumDetails() {
...
.when().get("/album/" + albumId)
...
}
}
P.S. Here are some more tips:
due to clean code more correct name describes what these methods do, e.g. getAlbumList() or storeAlbumList() and smth similar for another method;
for extracting jsonPath from response we can use: JsonPath js = given()....extract().jsonPath();

java.lang.IllegalStateExeption: Expectet a string but was BEGIN_ARRAY at line 1 column 16 path $[0].questions

I looked at some other threads about this topic and integrated the solution it offered but it still throws the same error. this is the first time i try to call an api on android. here i want to 'GET' an array of objects. There is no stack trace since the app does not crash. i think the problem has to do with the array of questions.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.100:3000/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<Post>> call = jsonPlaceHolderApi.getPosts();
call.enqueue(new Callback<List<Post>>() {
#Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
if (!response.isSuccessful()){
textViewResult.setText("Code: " + response.code());
return;
}
List<Post> posts = response.body();
for (Post post : posts){
String content = "";
content += "Doctor: " + post.getDoctor() + "\n";
content += "Name: " + post.getName() + "\n";
content += "Questions: " + post.getQuestions() + "\n\n";
textViewResult.append(content);
}
}
#Override
public void onFailure(Call<List<Post>> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
here is an example of the json data:
[
{
"questions":[...],
"_id":"5f42954a7e252b48ec3564b6",
"name":"Lifestyle",
"doctor":"doctoremail#gmail.com",
"__v":0
},
{
"questions":[...],
"_id":"5f4299687e252b48ec3564b7",
"name":"Headache",
"doctor":"doctoremail#gmail.com",
"__v":0
},
{
"questions":[...],
"_id":"5f429b2f7e252b48ec3564b9",
"name":"Foot pain",
"doctor":"doctoremail#gmail.com",
"__v":0
}
]
I fixed it. the problem was that the 'questions' property in my model was of type string in stead of List String
package com.example.medlog;
import java.util.List;
public class Post {
private String name;
private String doctor;
private List<String> questions;
public String getName() {
return name;
}
public String getDoctor() {
return doctor;
}
public List<String> getQuestions() {
return questions;
}
}

POST data with retrofit2, Bearer token Unauthorized android

I want to post new data to server with this JSON:
{
"tgl_Lahir": "1990-12-18 00:00:00",
"nama": "Joe",
"keterangan": "Employee",
"tempatLahir": "Los Angeles",
"noPegawai": "111111",
"golDarah": "0",
"statusNikah": "0",
"hubungans": {
"id": "10"
},
"agama": {
"id_Agama": "1"
},
"jeniskelamin": {
"jenisKelamin": "1"
}
}
Here's my ApiClientPOST.java:
public class ApiClientPOST {
private static Retrofit retrofit = null;
public static Retrofit getClient(String url){
if(retrofit == null){
retrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Here's my APIUtils.java:
public class APIUtils {
private APIUtils(){
};
public static final String API_URL = "IPAddress/employee/family/add";
public static MainInterface getUserService(){
return ApiClientPOST.getClient(API_URL).create(MainInterface.class);
}
}
Here's my familylistresponsePOST.java:
public class familylistresponsePOST {
#SerializedName("noPegawai")
private String noPegawai;
#SerializedName("date_otor")
private Object dateOtor;
#SerializedName("jeniskelamin")
private Jeniskelamin jeniskelamin;
#SerializedName("keterangan")
private String keterangan;
#SerializedName("hubungans")
private Hubungans hubungans;
#SerializedName("tgl_Lahir")
private String tglLahir;
#SerializedName("nama")
private String nama;
#SerializedName("agama")
private Agama agama;
#SerializedName("statusNikah")
private String statusNikah;
#SerializedName("tempatLahir")
private String tempatLahir;
#SerializedName("id")
private int id;
#SerializedName("golDarah")
private String golDarah;
public void setNoPegawai(String noPegawai){
this.noPegawai = noPegawai;
}
public String getNoPegawai(){
return noPegawai;
}
public void setDateOtor(Object dateOtor){
this.dateOtor = dateOtor;
}
public Object getDateOtor(){
return dateOtor;
}
public void setJeniskelamin(Jeniskelamin jeniskelamin){
this.jeniskelamin = jeniskelamin;
}
public Jeniskelamin getJeniskelamin(){
return jeniskelamin;
}
public void setKeterangan(String keterangan){
this.keterangan = keterangan;
}
public String getKeterangan(){
return keterangan;
}
public void setHubungans(Hubungans hubungans){
this.hubungans = hubungans;
}
public Hubungans getHubungans(){
return hubungans;
}
public void setTglLahir(String tglLahir){
this.tglLahir = tglLahir;
}
public String getTglLahir(){
return tglLahir;
}
public void setNama(String nama){
this.nama = nama;
}
public String getNama(){
return nama;
}
public void setAgama(Agama agama){
this.agama = agama;
}
public Agama getAgama(){
return agama;
}
public void setStatusNikah(String statusNikah){
this.statusNikah = statusNikah;
}
public String getStatusNikah(){
return statusNikah;
}
public void setTempatLahir(String tempatLahir){
this.tempatLahir = tempatLahir;
}
public String getTempatLahir(){
return tempatLahir;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setGolDarah(String golDarah){
this.golDarah = golDarah;
}
public String getGolDarah(){
return golDarah;
}
#Override
public String toString(){
return
"ListUserResponse2{" +
"noPegawai = '" + noPegawai + '\'' +
",date_otor = '" + dateOtor + '\'' +
",jeniskelamin = '" + jeniskelamin + '\'' +
",keterangan = '" + keterangan + '\'' +
",hubungans = '" + hubungans + '\'' +
",tgl_Lahir = '" + tglLahir + '\'' +
",nama = '" + nama + '\'' +
",agama = '" + agama + '\'' +
",statusNikah = '" + statusNikah + '\'' +
",tempatLahir = '" + tempatLahir + '\'' +
",id = '" + id + '\'' +
",golDarah = '" + golDarah + '\'' +
"}";
}
}
I've tried to create this method and use it on my Button.setOnClickListener:
public void addFamily(String noPegawai,String agama, String hubungan, String jenisKelamins, String tgl_Lahir, String nama, String keterangan, String tempatLahir, String golDarah, String statusNikah){
SharedPreferences preferences = getSharedPreferences("MyPref",0);
String tokens = preferences.getString("userToken",null);
Call<familylistresponse> call = apiService.addFams(noPegawai,agama, hubungan, jenisKelamins, tgl_Lahir , nama, keterangan, tempatLahir, golDarah, statusNikah, "Bearer" + tokens);
call.enqueue(new Callback<familylistresponse>() {
#Override
public void onResponse(Call<familylistresponse> call, Response<familylistresponse> response) {
// if (response.isSuccessful()){
familylistresponse resultsData = new familylistresponse();
resultsData= response.body();
Toast.makeText(TambahDataKeluarga.this,"Data Berhasil Ditambahkan!" + resultsData, Toast.LENGTH_SHORT).show();
// }
}
#Override
public void onFailure(Call<familylistresponse> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
}
This one is my tambah Button:
tambah.setOnClickListener(v -> {
SharedPreferences preferences = getSharedPreferences("MyPref",0);
String noPegawai = preferences.getString("noPegawai",null);
String snopeg = etNoPegawai.getText().toString().trim();
String snama = etNama.getText().toString().trim();
String stmpLahir = etTmptLahir.getText().toString().trim();
String stglLahir = etTglLahir.getText().toString().trim();
String sketerangan = etKeterangan.getText().toString().trim();
String sgoldar = etGoldar.getText().toString().trim();
String sstatusnikah = etStatusNikah.getText().toString().trim();
valueJenisKelamin = jeniskelamin.getSelectedItem().toString();
valueHubungan = spHubungans.getSelectedItem().toString();
valueAgama = spAgama.getSelectedItem().toString();
familylistresponse f = new familylistresponse();
f.setNoPegawai(snopeg);
agamas.setAgama(spAgama.getSelectedItem().toString().trim());
jks.setJenisKelamin(jeniskelamin.getSelectedItem().toString().trim());
hubungans.setHubungan(spHubungans.getSelectedItem().toString().trim());
addFamily(snopeg, valueAgama, valueHubungan, valueJenisKelamin, stglLahir, snama, sketerangan, stmpLahir, sgoldar, sstatusnikah);
Log.d(f.getNama(),f.getGolDarah());
Toast.makeText(TambahDataKeluarga.this,"No pegawai "+ noPegawai + " Nama Pegawai "+ snama+ " Tgl Lahir "+ stglLahir
+ " Agama " + valueAgama
+ " Hubungan " + valueHubungan
+ " Jenis Kelamin " + valueJenisKelamin
+ " Tgl Lahir " + stglLahir
+ " Keterangan " + sketerangan
+ " Tempat Lahir " + stmpLahir
+ " Goldar " + sgoldar
+ " Status Nikah " + sstatusnikah,Toast.LENGTH_LONG).show();
});
The toast says that the data is successfully stored but in fact, it isn't. The toast also says that response.body() is null and there is no error in logcat even in the debugger. Please kindly help me. Thanks in advance for any help
I do not see where you are defining Hubungans, Agama and Jeniskelamin classes although you are using it as datatype inside your familylistresponsePOST.java
After creating these three classes, I hope your issue will be solved.

Volley response Cannot store data into objects java android

My code is 100% working. I dont understand when i store the receiving output from Volley onresponse, i cant seem to store them correctly into my object. The raw output is correct. When i store it into my object, and then try to read the object, it showing wrong information.
For example, there is no data for contact and data for position is output at wrong place.
Log.d("TAG", "onResponse : "+ response.toString());
myProfile.set_firstname(response.optString("firstname", ""));
myProfile.set_lastname(response.optString("lastname", ""));
myProfile.set_contact(response.optString("contact", ""));
myProfile.set_email(response.optString("email", ""));
myProfile.set_position(response.optString("position", ""));
myProfile.set_areaname(response.optString("area", ""));
myProfile.set_deptname(response.optString("department", ""));
Log.d("TAG", "myProfile SET : " +
"firstname: "+myProfile.get_firstname() + " " +
"lastname: "+myProfile.get_lastname() + " " +
"contact: "+myProfile.get_contact() + " " +
"email: "+myProfile.get_email() + " " +
"position: "+myProfile.get_position() + " " +
"area: "+myProfile.get_areaname() + " " +
"dept: "+myProfile.get_deptname()
);
Raw JSON response from Volley and Log.d
onResponse : {"firstname":"kirpal","lastname":"SINGH","contact":"0164028083","email":"kirpal#gmail.com","position":"Technician","area":"Nextrack","department":"nexpro"}
myProfile SET : firstname: kirpal lastname: SINGH contact: Technician email: kirpal#gmail.com position: area: Nextrack dept: nexpro
MyProfile.java
public class MyProfile {
private String id="";
private String firstname="";
private String lastname="";
private String areaname ="";
private String deptname ="";
private String contact ="";
private String email ="";
private String position ="";
//SET
public void set_id(String id){this.id = id;}
public void set_firstname(String firstname){this.firstname = firstname;}
public void set_lastname(String lastname){this.lastname = lastname;}
public void set_areaname(String areaname){this.areaname = areaname;}
public void set_deptname(String deptname){this.deptname = deptname;}
public void set_contact(String contact){this.contact = contact;}
public void set_email(String email){this.email = email;}
public void set_position(String position){this.contact = position;}
//GET
public String get_id(){return this.id;}
public String get_firstname(){return this.firstname;}
public String get_lastname(){return this.lastname;}
public String get_areaname(){return this.areaname;}
public String get_deptname(){return this.deptname;}
public String get_contact(){return this.contact;}
public String get_email(){return this.email;}
public String get_position(){return this.position;}
}
Wrong info shows because you set position on contact and also set position on position.
public void set_position(String position){this.contact = position;}
change to
public void set_position(String position){this.position = position;}

com.google.gson.JsonSyntaxException: Expected a string but was BEGIN_OBJECT at line 1 column 18101 path $.data[0].groups[0]

I have found a lot of answers for this exception, but coudln't find one that helps my case.
I'm trying to use GSON to parse JSON. Here's my code:
public <T> T getObject(String[] caminho, String[] parametros, Class<T> tipoRetorno) {
T resultado = null;
WebResource webResource = getWebResource(caminho, parametros);
ClientResponse response = getBuilder(webResource).get(ClientResponse.class);
if (response.getStatus() == Status.OK.getStatusCode()) {
JSONObject json = null;
try {
json = new JSONObject(response.getEntity(String.class));
} catch (ClientHandlerException | UniformInterfaceException | JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resultado = new Gson().fromJson(json.toString(), tipoRetorno);
} else if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) {
String msg = "Getting cross-connections. URI: " + webResource.getURI() + " status: " + response.getStatus()
+ " " + response.getStatusInfo();
logger.info(msg);
} else {
String msg = "Error getting cross-connections. URI: " + webResource.getURI() + " returned error : "
+ response.getStatus() + " status: " + response.getStatusInfo();
logger.info(msg);
}
return resultado;
}
Here's the JSON returned from the 'json':
{"data":[{"thumbs":[{"id":79204454,"updated_at":"2016-12-24T19:54:48.000Z","created_at":"2016-12-24T19:54:48.000Z","filename":"54857bd6-0ccc-48d2-b5c8-8c4483954789_1482608998509","test_case_id":8172839,"url":"https://s3-eu-west-1.amazonaws.com/euthumbtestingbot/54857bd6-0ccc-48d2-b5c8-8c4483954789_1482608998509.jpg","custom":false},{"id":79204455,"updated_at":"2016-12-24T19:54:48.000Z","created_at":"2016-12-24T19:54:48.000Z","filename":"54857bd6-0ccc-48d2-b5c8-8c4483954789_1482609000499","test_case_id":8172839,"url":"https://s3-eu-west-1.amazonaws.com/euthumbtestingbot/54857bd6-0ccc-48d2-b5c8-8c4483954789_1482609000499.jpg","custom":false},{"id":79204456,"updated_at":"2016-12-24T19:54:48.000Z","created_at":"2016-12-24T19:54:48.000Z","filename":"54857bd6-0ccc-48d2-b5c8-8c4483954789_1482609001762","test_case_id":8172839,"url":"https://s3-eu-west-1.amazonaws.com/euthumbtestingbot/54857bd6-0ccc-48d2-b5c8-8c4483954789_1482609001762.jpg","custom":false}...}
And 'tipoRetorno' is class br.usp.icmc.testingbot.beans.AgrupamentoTestes:
package br.usp.icmc.testingbot.beans;
import java.util.List;
public class AgrupamentoTestes {
private List<Teste> data;
private Meta meta;
public List<Teste> getData() {
return data;
}
public void setData(List<Teste> data) {
this.data = data;
}
public Meta getMeta() {
return meta;
}
public void setMeta(Meta meta) {
this.meta = meta;
}
}
I'm getting this exception:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 18101 path $.data[0].groups[0]
Why can't Gson properly convert my JSON text to my POJO type?
If you paste the string into a text editor, you'll be able to see row and column numbers at the bottom, and find column 18101 where the error is.

Categories

Resources