i really ned help with this. Im not being able to read the JSON and i dont know what im doing wrong.
I will drop my code here.
I have this Json
{
"id": "288",
"name": "Tarjeta Shopping",
"secure_thumbnail": "https://www.mercadopago.com/org-img/MP3/API/logos/288.gif",
"thumbnail": "http://img.mlstatic.com/org-img/MP3/API/logos/288.gif",
"processing_mode": "aggregator",
"merchant_account_id": null
}
This is my class that should represent that JSON
public class Tarjeta {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("secure_thumbnail")
#Expose
private String secureThumbnail;
#SerializedName("thumbnail")
#Expose
private String thumbnail;
#SerializedName("processing_mode")
#Expose
private String processingMode;
#SerializedName("merchant_account_id")
#Expose
private Object merchantAccountId;
public Tarjeta() {
}
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 getSecureThumbnail() {
return secureThumbnail;
}
public void setSecureThumbnail(String secureThumbnail) {
this.secureThumbnail = secureThumbnail;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getProcessingMode() {
return processingMode;
}
public void setProcessingMode(String processingMode) {
this.processingMode = processingMode;
}
public Object getMerchantAccountId() {
return merchantAccountId;
}
public void setMerchantAccountId(Object merchantAccountId) {
this.merchantAccountId = merchantAccountId;
}
#Override
public String toString() {
return "Tarjeta{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", secureThumbnail='" + secureThumbnail + '\'' +
", thumbnail='" + thumbnail + '\'' +
", processingMode='" + processingMode + '\'' +
", merchantAccountId=" + merchantAccountId +
'}';
}
}
this is my GET method
#GET("payment_methods/card_issuers")
Call<Tarjeta> getTarjetas2(#Query("public_key") String apiKey,
#Query("payment_method_id") String payment_method_id);
And this is where i try to read it.
botonTest2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Test boton 2 clickeado");
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ServicePago servicePago = retrofit.create(ServicePago.class);
Call<Tarjeta> contenedorTarjetaCall = servicePago.getTarjetas2(apiKey,"visa");
contenedorTarjetaCall.enqueue(new Callback<Tarjeta>() {
#Override
public void onResponse(Call<Tarjeta> call, Response<Tarjeta> response) {
Toast.makeText(MainActivity.this, "BIEN", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<Tarjeta> call, Throwable t) {
Toast.makeText(MainActivity.this, "ALGO SALIO MAL", Toast.LENGTH_SHORT).show();
}
});
}
});
Im habing this error: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
I think my class is correctly modelated, im completly lost.
since you did not post your entire JSON I'm going to answer with a rough idea hope it helps.
the error states that the received JSON is not a Tarjeta but an array of Tarjeta. so to fix it I guess you just have to wrap your response in a list type. so it goes something like this:
#GET("payment_methods/card_issuers")
Call<List<Tarjeta>> getTarjetas2(#Query("public_key") String apiKey,
#Query("payment_method_id") String payment_method_id);
Related
I am making a java file in which you enter the country and then it shows you the covid-19 info of that country. The site which I am using is https://covid19.mathdro.id/api/countries/
here i want it such that the user enter the country and it adds the countries name to the website eg if the user entered India it should do this
https://covid19.mathdro.id/api/countries/India
Any help would be neccessary, Thanks
You can use Retrofit to call the APIs
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import retrofit2.Response;
public class Retrofit_Example {
public static void main(String[] args) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://covid19.mathdro.id/")
.addConverterFactory(GsonConverterFactory.create())
.client(client.build())
.build();
Service service = retrofit.create(Service.class);
Call<Response1> responseCall = service.getData("India");
try {
Response<Response1> response = responseCall.execute();
Response1 apiResponse = response.body();
System.out.println(apiResponse);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You will have to create POJOs from the JSON response coming from the api first and also the retrofit client.
POJO for respone
public class Response1 {
private Confirmed confirmed;
private Deaths deaths;
private String lastUpdate;
private Recovered recovered;
public Confirmed getConfirmed() {
return confirmed;
}
public void setConfirmed(Confirmed confirmed) {
this.confirmed = confirmed;
}
public Deaths getDeaths() {
return deaths;
}
public void setDeaths(Deaths deaths) {
this.deaths = deaths;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public Recovered getRecovered() {
return recovered;
}
public void setRecovered(Recovered recovered) {
this.recovered = recovered;
}
#Override
public String toString() {
return "Response1{" +
"confirmed=" + confirmed +
", deaths=" + deaths +
", lastUpdate='" + lastUpdate + '\'' +
", recovered=" + recovered +
'}';
}
}
public class Recovered {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Recovered{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
public class Deaths {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Deaths{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
public class Confirmed {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Confirmed{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
Retrofit Client
public interface Service {
#GET("/api/countries/{country}")
public Call<Response1> getData(#Path("country")String country);
}
I want to parse json which I send to my phone. this is what I get :
In params I get two string
UPDATE_ROUTE
and
[{"card_id":"3a296050-b7dc-4f7b-a041-162817090520","t_tasks_e_dic_load_types_sj_id":132,"status_id":2,"eup":"86baeff7e","card_nr":"211","change_time":"2019-12-17T12:04:43.129Z"}]
this is my class :
public class FCMResponse{
#SerializedName("data")
private List<DataItem> data;
#SerializedName("type")
private String type;
}
I try do this :
FCMResponse fcm = g.fromJson("\"data\":"+updateResponse.getData(), FCMResponse.class);
but when I try parse this or try parse string to my java class I get :
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $
According to this response,
[{"card_id":"3a296050-b7dc-4f7b-a041-162817090520","t_tasks_e_dic_load_types_sj_id":132,"status_id":2,"eup":"86baeff7e","card_nr":"211","change_time":"2019-12-17T12:04:43.129Z"}]
your model class should be
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("card_id")
#Expose
private String cardId;
#SerializedName("t_tasks_e_dic_load_types_sj_id")
#Expose
private Integer tTasksEDicLoadTypesSjId;
#SerializedName("status_id")
#Expose
private Integer statusId;
#SerializedName("eup")
#Expose
private String eup;
#SerializedName("card_nr")
#Expose
private String cardNr;
#SerializedName("change_time")
#Expose
private String changeTime;
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public Integer getTTasksEDicLoadTypesSjId() {
return tTasksEDicLoadTypesSjId;
}
public void setTTasksEDicLoadTypesSjId(Integer tTasksEDicLoadTypesSjId) {
this.tTasksEDicLoadTypesSjId = tTasksEDicLoadTypesSjId;
}
public Integer getStatusId() {
return statusId;
}
public void setStatusId(Integer statusId) {
this.statusId = statusId;
}
public String getEup() {
return eup;
}
public void setEup(String eup) {
this.eup = eup;
}
public String getCardNr() {
return cardNr;
}
public void setCardNr(String cardNr) {
this.cardNr = cardNr;
}
public String getChangeTime() {
return changeTime;
}
public void setChangeTime(String changeTime) {
this.changeTime = changeTime;
}
#Override
public String toString() {
return "Example{" +
"cardId='" + cardId + '\'' +
", tTasksEDicLoadTypesSjId=" + tTasksEDicLoadTypesSjId +
", statusId=" + statusId +
", eup='" + eup + '\'' +
", cardNr='" + cardNr + '\'' +
", changeTime='" + changeTime + '\'' +
'}';
}
}
And you can fetch in class like,
Gson gson = new Gson();
Example[] examples = gson.fromJson(response, Example[].class);
Example example = examples[0];
I have some issues with Retrofit2 while posting data to an API using POST request.
The response from the server is successful but all the values displayed on the response are null :
I/SUCCESS: test : Post{id='null', titre='null', description='null', prix='null', pseudo='null', emailContact='null', telContact='null', ville='null', cp='null', image='null', date='null'}
Here is an example of the JSON that I've to receive
{
"success": true,
"response": {
"id": “5a5f11196c2aa”,
"titre": "Vends 406",
"description": "Pas chere",
"prix": "4500",
"pseudo": "jml",
"emailContact": "",
"telContact": "Vends 406",
"ville": "",
"cp": "",
"images": [],
"date": 1516179737
}
}
Here is my data model :
public class Post {
#SerializedName("cp")
private String cp;
#SerializedName("date")
private Long date;
#SerializedName("description")
private String description;
#SerializedName("emailContact")
private String emailContact;
#SerializedName("id")
private String id;
#SerializedName("images")
private String[] images;
#SerializedName("prix")
private String prix;
#SerializedName("pseudo")
private String pseudo;
#SerializedName("telContact")
private String telContact;
#SerializedName("titre")
private String titre;
#SerializedName("ville")
private String ville;
public String getCp() {
return cp;
}
public void setCp(String cp) {
this.cp = cp;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEmailContact() {
return emailContact;
}
public void setEmailContact(String emailContact) {
this.emailContact = emailContact;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String[] getImages() {
return images;
}
public void setImages(String[] images) {
this.images = images;
}
public String getPrix() {
return prix;
}
public void setPrix(String prix) {
this.prix = prix;
}
public String getPseudo() {
return pseudo;
}
public void setPseudo(String pseudo) {
this.pseudo = pseudo;
}
public String getTelContact() {
return telContact;
}
public void setTelContact(String telContact) {
this.telContact = telContact;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
#Override
public String toString(){
return "Post{" +
"id='" + getId() + '\'' +
", titre='" + getTitre() + '\'' +
", description='" + getDescription() + '\'' +
", prix='" + getPrix() + '\'' +
", pseudo='" + getPseudo() + '\'' +
", emailContact='" + getEmailContact() + '\'' +
", telContact='" + getTelContact() + '\'' +
", ville='" + getVille() + '\'' +
", cp='" + getCp() + '\'' +
", image='" + getImages() + '\'' +
", date='" + getDate() + '\'' +
'}';
}}
Here is my Retrofit Instance :
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().serializeNulls().create()))
.build();
Here is my API Service Interface :
public interface APIService {
#POST("/android-api")
#FormUrlEncoded
Call<Post> savePost(#Field("apikey") String apikey,
#Field("method") String method,
#Field("titre") String title,
#Field("description") String description,
#Field("prix") String prix,
#Field("pseudo") String pseudo,
#Field("emailContact") String emailContact,
#Field("telContact") String telContact,
#Field("ville") String ville,
#Field("cp") String cp,
#Field("images") String[] images
);}
And here is my sendPost method :
public void sendPost(String title, String prix, String cp, String ville, String description) {
// On récupère ici les préférences de l'utilisateur
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String pseudo = preferences.getString("pseudo", "DEFAULT");
String emailContact = preferences.getString("mail", "DEFAULT");
String telContact = preferences.getString("tel", "DEFAULT");
// Provisoire
String[] images = {} ;
mAPIService.savePost(APIKEY,METHOD,title,description,prix,pseudo,emailContact,telContact,ville,cp,images).enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
if(response.isSuccessful()) {
showResponse(response.body().toString());
Log.i("SUCCESS", "test : "+ response.body().toString());
}
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
Log.e("FAIL", "Unable to submit post to API.");
}
});}
Thank you in advance for helping me
I recently used retrofit to retrieve data...
First used http://www.jsonschema2pojo.org/ to create a model class from your possible outcome JSON response .
And I used Retrofit instance--
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client =
new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
I've tried pass object between activities exactly like in How to pass an object from one activity to another on Android
and SerializableTask is creating correctly but when I want to read this in next activity it is null.
Task task = listOfTask.get(position);
Log.i(TAG, "recyclerViewEditTask: edit clicked for title: " +
task.getTitle());
SerializabledTask sTask = new SerializabledTask(task.getTitle(),
task.getDetails(), task.getTimeToDo(), task.getTag(),
task.getId(), task.isDone());
if(sTask == null)
Log.e(TAG, "recyclerViewEditTask: sTask IS NULL");
else {
Log.i(TAG, "recyclerViewEditTask: sTaskInfo: " + sTask.toString());
Intent editIntent = new Intent(ListOfTasksActivity.this, EditTaskActivity.class);
editIntent.putExtra("task", sTask);
startActivity(editIntent);
then it goes to another activity
activity that try to get Serializable object:
Intent i = getIntent();
SerializabledTask sTask = (SerializabledTask) i.getSerializableExtra("task");
if(sTask == null)
Log.e(TAG, "onCreate: sTASK IS NULL" );
and "onCreate: sTASK IS NULL" is calling
when I tried to pass single String it works properly
Serializables class:
public class SerializabledTask implements Serializable {
String title, details, timeToDo, tag;
int id;
boolean done;
Task task;
public SerializabledTask(String title, String details, String timeToDo, String tag, int id, boolean done) {
this.title = title;
this.details = details;
this.timeToDo = timeToDo;
this.tag = tag;
this.id = id;
this.done = done;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getTimeToDo() {
return timeToDo;
}
public void setTimeToDo(String timeToDo) {
this.timeToDo = timeToDo;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
#Override
public String toString() {
return "SerializabledTask{" +
"title='" + title + '\'' +
", details='" + details + '\'' +
", timeToDo='" + timeToDo + '\'' +
", tag='" + tag + '\'' +
", id=" + id +
", done=" + done +
", task=" + task +
'}';
}
Your model class SerializableTask must implement Serializable for your code to work.
public class SerializableTask implements Serializable {
...
}
Also it's highly recommended to use Parcelable instead of Serializable, because it's a lot faster.
Source : http://www.developerphil.com/parcelable-vs-serializable/
I am using Spring Social FqlQuery to get data's from facebook. Here is the JSON response I am getting from facebook. My controller where i am getting Json output is here,
fql = "SELECT work FROM user WHERE uid = me()";
facebook.fqlOperations().query(fql, new FqlResultMapper<Object>() {
public Object mapObject(FqlResult result) {
List list = (List) result.getObject("work");
for (Object object : list) {
JsonHelper jsonHelper = new JsonHelper();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(object);
System.out.println(jsonOutput);
gson.fromJson(jsonOutput, JsonHelper.class);
}
System.out.println inside for loop Outputs multiple json as below.:
{
"employer": {
"id": 129843057436,
"name": "www.metroplots.com"
},
"location": {
"id": 102186159822587,
"name": "Chennai, Tamil Nadu"
},
"position": {
"id": 108480125843293,
"name": "Web Developer"
},
"start_date": "2012-10-01",
"end_date": "2013-05-31"
}
{
"employer": {
"id": 520808381292985,
"name": "Federation of Indian Blood Donor Organizations"
},
"start_date": "0000-00",
"end_date": "0000-00"
}
Here is my Helper Class:
import java.util.List;
public class JsonHelper {
class Employer{
private int id;
private String name;
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;
}
}
class Location{
private int id;
private String name;
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;
}
}
class Position{
private int id;
private String name;
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;
}
}
//Edited After here
private String start_Date;
private String end_Date;
private Employer employer;
private Location location;
private Position position;
public String getStart_Date() {
return start_Date;
}
public void setStart_Date(String start_Date) {
this.start_Date = start_Date;
}
public String getEnd_Date() {
return end_Date;
}
public void setEnd_Date(String end_Date) {
this.end_Date = end_Date;
}
public Employer getEmployer() {
return employer;
}
public void setEmployer(Employer employer) {
this.employer = employer;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
}
When I try to convert the json objects to java object as done above I am getting this exception.
HTTP Status 500 - Request processing failed; nested exception is com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 6 column 16
Can any one help me where I am wrong. Please help me converting json to java objects. Hope my question is clear. Thanks in advance.
EDIT MADE TO CONTROLLER:
facebook.fqlOperations().query(fql, new FqlResultMapper<Object>() {
public Object mapObject(FqlResult result) {
List<JsonHelper> json = new ArrayList<JsonHelper>();
List list = (List) result.getObject("work");
for (Object object : list) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(object);
System.out.println(jsonOutput);
JsonHelper jsonHelper = gson.fromJson(jsonOutput, JsonHelper.class);
json.add(jsonHelper);
System.out.println(jsonHelper.getStart_Date());
}
for (JsonHelper jsonHelper : json) {
System.out.println(jsonHelper.getStart_Date());
}
return list;
}
});
Since i am not having the actual api access, so i am trying it with static value in the example. Firstly in your JsonHelper class, replace all int by long , as the values mentioned in the json are of type long and String. Then try it like mentioned below:
String str = "{\n"
+ " \"employer\": {\n"
+ " \"id\": 129843057436,\n"
+ " \"name\": \"www.metroplots.com\"\n"
+ " },\n"
+ " \"location\": {\n"
+ " \"id\": 102186159822587,\n"
+ " \"name\": \"Chennai, Tamil Nadu\"\n"
+ " },\n"
+ " \"position\": {\n"
+ " \"id\": 108480125843293,\n"
+ " \"name\": \"Web Developer\"\n"
+ " },\n"
+ " \"start_date\": \"2012-10-01\",\n"
+ " \"end_date\": \"2013-05-31\"\n"
+ "}";
List<JsonHelper> json = new ArrayList<JsonHelper>();
Gson gson = new Gson();
JsonHelper users = gson.fromJson(str, JsonHelper.class);
json.add(users);
for (JsonHelper js_obj : json) {
System.out.println(js_obj.getEmployer().getId());
System.out.println(js_obj.getEmployer().getName());
}