hello i have Json response like this
[
{
"question": "hhhhh",
"question_answer": "hhhh ",
"question_type": "question type",
"questioner_age": "questioner age",
"questioner_city": "questioner city",
"questioner_country": "questioner country",
"questioner_name": "questioner name",
"questioner_sex": "questioner sex",
"comments_allowed": "1",
"question_id": "63",
"question_date": "05/08/2017 - 19:33",
"is_public": "1"
},
{
"question": "hhhh !!",
"question_answer": "hhhh",
"question_type": [],
"questioner_age": [],
"questioner_city": [],
"questioner_country": [],
"questioner_name": "hhhhh",
"questioner_sex": [],
"comments_allowed": "1",
"question_id": "57",
"question_date": "04/30/2017 - 14:24",
"is_public": "1"
}
]
if the column is null will return as an array like this "question_type": [],
if not will return as a string !
so i tried to get this response on retrofit but i failed and always got this error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 4 column 2 path $
after i searched in the internet i tried something like this but its not working !!
Gson gson = new Gson();
String json = response.body().toString();
if (json instanceof String)
{
MyQuestionModelString parseObject = gson.fromJson(json, MyQuestionModelString.class);
apiCallResponse.onSuccess(parseObject,responseMessage);
}else {
MyQuestionModel parseObject = gson.fromJson(json, MyQuestionModel.class);
apiCallResponse.onSuccess(parseObject,responseMessage);
}
any help !
UPDATAE !
this is my model for this response and same error !!!
public class MyQuestionModel {
#SerializedName("question")
#Expose
private String question;
#SerializedName("question_answer")
#Expose
private String questionAnswer;
#SerializedName("question_type")
#Expose
private List<Object> questionType = null;
#SerializedName("questioner_age")
#Expose
private List<Object> questionerAge = null;
#SerializedName("questioner_city")
#Expose
private List<Object> questionerCity = null;
#SerializedName("questioner_country")
#Expose
private List<Object> questionerCountry = null;
#SerializedName("questioner_name")
#Expose
private String questionerName;
#SerializedName("questioner_sex")
#Expose
private List<Object> questionerSex = null;
#SerializedName("comments_allowed")
#Expose
private String commentsAllowed;
#SerializedName("question_id")
#Expose
private String questionId;
#SerializedName("question_date")
#Expose
private String questionDate;
#SerializedName("is_public")
#Expose
private String isPublic;
}
My Main issue that how to define this field ! question_type
screen shot
During the parsing of json if the SerializedName key is not found it will throw an exception. Use #Expose to let the deserializer to know that this field can be null. Here is a similar Model of your mentioned response
public class ResponsePojo {
List<Data> data;
public class Data {
#Expose
#SerializedName("question")
String question;
#Expose
#SerializedName("question_answer")
String questionAnswer;
#Expose
#SerializedName("question_type")
String questionType;
#Expose
#SerializedName("questioner_age")
String questionerAge;
#Expose
#SerializedName("questioner_city")
String questionerCity;
#Expose
#SerializedName("questioner_country")
String questionerCountry;
#Expose
#SerializedName("questioner_name")
String questionerName;
#Expose
#SerializedName("questioner_sex")
String questionerSex;
#Expose
#SerializedName("comments_allowed")
String commentsAllowed;
#Expose
#SerializedName("question_id")
String questionId;
#Expose
#SerializedName("question_date")
String questionDate;
#Expose
#SerializedName("is_public")
String isPublic;
}
}
You must indicate which paramters or objects in the model are optional with #Exposed tag.
Example
#Expose
#SerializedName("question_type")
private String mQuestionType;
You problem is
ava.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 4 column 2 path $
If your json code is [...],your return is JSONArray , you can use Gsonto parse it to List<Object> .
If your json code is {...},your return is JSONObject , you can use Gsonto parse it to Object .
So you should use List<MyQuestionModel> to get parsed data .
Change MyQuestionModel to List<MyQuestionModel> in your call code .
Sample
Call<List<MyQuestionModel>> getData();
And my code for doing it .
JSONEntity for you json
public class JSONEntity {
/**
* question : hhhhh
* question_answer : hhhh
* question_type : question type
* questioner_age : questioner age
* questioner_city : questioner city
* questioner_country : questioner country
* questioner_name : questioner name
* questioner_sex : questioner sex
* comments_allowed : 1
* question_id : 63
* question_date : 05/08/2017 - 19:33
* is_public : 1
*/
private String question;
private String question_answer;
private String question_type;
private String questioner_age;
private String questioner_city;
private String questioner_country;
private String questioner_name;
private String questioner_sex;
private String comments_allowed;
private String question_id;
private String question_date;
private String is_public;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getQuestion_answer() {
return question_answer;
}
public void setQuestion_answer(String question_answer) {
this.question_answer = question_answer;
}
public String getQuestion_type() {
return question_type;
}
public void setQuestion_type(String question_type) {
this.question_type = question_type;
}
public String getQuestioner_age() {
return questioner_age;
}
public void setQuestioner_age(String questioner_age) {
this.questioner_age = questioner_age;
}
public String getQuestioner_city() {
return questioner_city;
}
public void setQuestioner_city(String questioner_city) {
this.questioner_city = questioner_city;
}
public String getQuestioner_country() {
return questioner_country;
}
public void setQuestioner_country(String questioner_country) {
this.questioner_country = questioner_country;
}
public String getQuestioner_name() {
return questioner_name;
}
public void setQuestioner_name(String questioner_name) {
this.questioner_name = questioner_name;
}
public String getQuestioner_sex() {
return questioner_sex;
}
public void setQuestioner_sex(String questioner_sex) {
this.questioner_sex = questioner_sex;
}
public String getComments_allowed() {
return comments_allowed;
}
public void setComments_allowed(String comments_allowed) {
this.comments_allowed = comments_allowed;
}
public String getQuestion_id() {
return question_id;
}
public void setQuestion_id(String question_id) {
this.question_id = question_id;
}
public String getQuestion_date() {
return question_date;
}
public void setQuestion_date(String question_date) {
this.question_date = question_date;
}
public String getIs_public() {
return is_public;
}
public void setIs_public(String is_public) {
this.is_public = is_public;
}
}
And the code for parse it .
Gson gson = new Gson();
String jsonString = response.body().string();
Type type = new TypeToken<List<JSONEntity>>() {
}.getType();
List<JSONEntity> datas = gson.fromJson(jsonString, type);
EDIT
If your response is JSONArray , you can try like this .
List<JSONEntity> datas = response.body();
Try to change your JSON Structure
First Approach
To
If the column is null return "question_type": null,else show "question_type": "value"
Instead
If the column is null will return as an array like this "question_type": [], if not will return as a string!
Second Approach Without changing Json structure
Handling Dynamic JSON Using Gson
Try this:
You have to use deserialize to parse dynamic datatype in json
In the reponse pojo use object
Ex:
Call<Object> call = //your API call ResponsePojo instead use `Object`
call.enqueue(new Callback<Object>()
{
#Override
public void onResponse(Response<Object> response, Retrofit retrofit)
{
try {
JSONArray jsonArray=new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(ServerResponse.class, new ServerResponse.OptionsDeserilizer())
.create();
ServerResponse serverResponse=gson.fromJson(jsonArray.get(i).toString(), ServerResponse.class);
System.out.println(serverResponse);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t)
{
///Handle failure
}
});
Use this ServerResponsePojo with JsonDeserializer
import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class ServerResponse {
#SerializedName("question")
#Expose
private String question;
#SerializedName("question_answer")
#Expose
private String questionAnswer;
private String questionerName;
#SerializedName("comments_allowed")
#Expose
private String commentsAllowed;
#SerializedName("question_id")
#Expose
private String questionId;
#SerializedName("question_date")
#Expose
private String questionDate;
#SerializedName("is_public")
#Expose
private String isPublic;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getQuestionAnswer() {
return questionAnswer;
}
public void setQuestionAnswer(String questionAnswer) {
this.questionAnswer = questionAnswer;
}
/* public List<OptionValue> getQuestionerAge() {
return questionerAge;
}
public void setQuestionerAge(List<OptionValue> questionerAge) {
this.questionerAge = questionerAge;
}
public List<OptionValue> getQuestionerCity() {
return questionerCity;
}
public void setQuestionerCity(List<OptionValue> questionerCity) {
this.questionerCity = questionerCity;
}
public List<OptionValue> getQuestionerCountry() {
return questionerCountry;
}
public void setQuestionerCountry(List<OptionValue> questionerCountry) {
this.questionerCountry = questionerCountry;
}
*/
public String getQuestionerName() {
return questionerName;
}
public void setQuestionerName(String questionerName) {
this.questionerName = questionerName;
}
/*
public List<OptionValue> getQuestionerSex() {
return questionerSex;
}
public void setQuestionerSex(List<OptionValue> questionerSex) {
this.questionerSex = questionerSex;
}*/
public String getCommentsAllowed() {
return commentsAllowed;
}
public void setCommentsAllowed(String commentsAllowed) {
this.commentsAllowed = commentsAllowed;
}
public String getQuestionId() {
return questionId;
}
public void setQuestionId(String questionId) {
this.questionId = questionId;
}
public String getQuestionDate() {
return questionDate;
}
public void setQuestionDate(String questionDate) {
this.questionDate = questionDate;
}
public String getIsPublic() {
return isPublic;
}
public void setIsPublic(String isPublic) {
this.isPublic = isPublic;
}
public class OptionValue {
}
public void setQuestionType(String questionType) {
this.questionType = questionType;
}
String questionType;
public static class OptionsDeserilizer implements JsonDeserializer<ServerResponse> {
#Override
public ServerResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Type listType = new TypeToken<ServerResponse>() {
}.getType();
ServerResponse options = (ServerResponse) new Gson().fromJson(json, listType);
JsonObject jsonArrayValue = json.getAsJsonObject();
for (int i = 0; i < jsonArrayValue.size(); i++) {
JsonObject jsonObject = jsonArrayValue.getAsJsonObject();
if (jsonObject.has("question_type")) {
JsonElement elem = (JsonElement) jsonObject.get("question_type");
if (elem != null && !elem.isJsonNull() && !elem.isJsonArray()) {
String valuesString = elem.getAsString();
if (!TextUtils.isEmpty(valuesString)) {
options.setQuestionType(valuesString);
} else {
options.setQuestionType("");
}
//Do your other stuffs
}
}
}
return options;
}
}
}
This is working happy codeing
Related
[
{
"login": "mojombo",
"id": 1,
"node_id": "MDQ6VXNlcjE=",
"avatar_url": "https://avatars0.githubusercontent.com/u/1?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/mojombo",
"html_url": "https://github.com/mojombo",
"followers_url": "https://api.github.com/users/mojombo/followers",
"following_url": "https://api.github.com/users/mojombo/following{/other_user}",
"gists_url": "https://api.github.com/users/mojombo/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mojombo/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mojombo/subscriptions",
"organizations_url": "https://api.github.com/users/mojombo/orgs",
"repos_url": "https://api.github.com/users/mojombo/repos",
"events_url": "https://api.github.com/users/mojombo/events{/privacy}",
"received_events_url": "https://api.github.com/users/mojombo/received_events",
"type": "User",
"site_admin": false
}
]
Json: https://api.github.com/users
This is URL of an API... how can i parse this object to fetch the data using retrofit?
Here is the example on how to fetch JSON object with array using retrofit. I believe you won't have troubles changing it to work with your data.
Example.java
public class Example {
#SerializedName("PnrNumber")
#Expose
private String pnrNumber;
#SerializedName("Status")
#Expose
private String status;
#SerializedName("ResponseCode")
#Expose
private String responseCode;
#SerializedName("TrainNumber")
#Expose
private String trainNumber;
#SerializedName("TrainName")
#Expose
private String trainName;
#SerializedName("JourneyClass")
#Expose
private String journeyClass;
#SerializedName("ChatPrepared")
#Expose
private String chatPrepared;
#SerializedName("From")
#Expose
private String from;
#SerializedName("To")
#Expose
private String to;
#SerializedName("JourneyDate")
#Expose
private String journeyDate;
#SerializedName("Passangers")
#Expose
private List<Passanger> passangers = null;
public String getPnrNumber() {
return pnrNumber;
}
public void setPnrNumber(String pnrNumber) {
this.pnrNumber = pnrNumber;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getResponseCode() {
return responseCode;
}
public void setResponseCode(String responseCode) {
this.responseCode = responseCode;
}
public String getTrainNumber() {
return trainNumber;
}
public void setTrainNumber(String trainNumber) {
this.trainNumber = trainNumber;
}
public String getTrainName() {
return trainName;
}
public void setTrainName(String trainName) {
this.trainName = trainName;
}
public String getJourneyClass() {
return journeyClass;
}
public void setJourneyClass(String journeyClass) {
this.journeyClass = journeyClass;
}
public String getChatPrepared() {
return chatPrepared;
}
public void setChatPrepared(String chatPrepared) {
this.chatPrepared = chatPrepared;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getJourneyDate() {
return journeyDate;
}
public void setJourneyDate(String journeyDate) {
this.journeyDate = journeyDate;
}
public List<Passanger> getPassangers() {
return passangers;
}
public void setPassangers(List<Passanger> passangers) {
this.passangers = passangers;
}
}
Passanger.Java
public class Passanger {
#SerializedName("Passenger")
#Expose
private String passenger;
#SerializedName("BookingStatus")
#Expose
private String bookingStatus;
#SerializedName("CurrentStatus")
#Expose
private String currentStatus;
public String getPassenger() {
return passenger;
}
public void setPassenger(String passenger) {
this.passenger = passenger;
}
public String getBookingStatus() {
return bookingStatus;
}
public void setBookingStatus(String bookingStatus) {
this.bookingStatus = bookingStatus;
}
public String getCurrentStatus() {
return currentStatus;
}
public void setCurrentStatus(String currentStatus) {
this.currentStatus = currentStatus;
}
}
Here are the classes which are generated from the Response which you have provided in the question.
You can use this link to generate the POJO class for JSON response.
JSON TO POJO
Add this gradle:
implementation 'com.google.code.gson:gson:2.8.2'
Init the Gson buildr:
private Gson gson;
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
gson = gsonBuilder.create();
Parse the JSON using GSON
gson.fromJson(jsonObject.getJSONObject("data").toString(), Example.class);
These are the basic steps to parse the JSON using GSON.
For more information you can refer to the below article:
Parsing JSON on Android using GSON
Or Check the GSON official GitHub Repository
GSON
I am trying to use Jackson to parse sample json as demonstrated below. However, I the parsing doesn't work (fails without any exceptions - as I get an empty string for event.getAccountId(); What could I be doing wrong?
Thanks!
ObjectMapper om = new ObjectMapper();
String json = "{\"_procurementEvent\" : [{ \"accountId\" : \"3243234\",\"procurementType\" : \"view\"," +
"\"_procurementSubType\" : \"Standard Connector\",\"_quantity\" : \"4\", \"_pricePerMonth\" : \"100.00\"" +
",\"_annualPrice\" : \"1200.00\"}]}";
ProcurementEvent event = om.readValue(json, ProcurementEvent.class);
event.getAccountId(); // returns null
#JsonIgnoreProperties(ignoreUnknown = true)
private static class ProcurementEvent {
private String _accountId;
private String _procurementType;
private String _quantity;
private String _pricePerMonth;
private String _annualPrice;
#JsonProperty("accountId")
public String getAccountId() {
return _accountId;
}
public void setAccountId(String accountId) {
_accountId = accountId;
}
#JsonProperty("procurementType")
public String getProcurementType() {
return _procurementType;
}
public void setProcurementType(String procurementType) {
_procurementType = procurementType;
}
#JsonProperty("_quantity")
public String getQuantity() {
return _quantity;
}
public void setQuantity(String quantity) {
_quantity = quantity;
}
#JsonProperty("_pricePerMonth")
public String getPricePerMonth() {
return _pricePerMonth;
}
public void setPricePerMonth(String pricePerMonth) {
_pricePerMonth = pricePerMonth;
}
#JsonProperty("_annualPrice")
public String getAnnualPrice() {
return _annualPrice;
}
public void setAnnualPrice(String annualPrice) {
_annualPrice = annualPrice;
}
}
In the question, try the following approach:
class ProcurementEvents {
private List<ProcurementEvent> _procurementEvent; // + annotations like #JsonIgnoreProperties, getters/ setters, etc.
}
// json from your example
ProcurementEvents events = om.readValue(json, ProcurementEvents.class);
events.get(0).getAccountId();
I Am Having two JsonArray in Which there is JsonObject I have Got the String of each value but the problem is that when i am passing i into adapter I am getting indexOutofbound exeption because my value are getting Store in my object class so can any one help me how can i send my data to Object so that i can inflate to recyclerView.
private void callola() {
progressDialog = new ProgressDialog(CabBookingActivity.this);
progressDialog.setMessage("Loading ...");
progressDialog.setCancelable(false);
progressDialog.show();
final RequestQueue queue = Volley.newRequestQueue(CabBookingActivity.this);
String url = "https://www.reboundindia.com/app/application/ola/ride_estimate.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.setCancelable(true);
progressDialog.dismiss();
Log.e("sushil Call ola response", response);
try {
JSONObject mainObj = new JSONObject(response);
arrayList = new ArrayList<>();
String result = mainObj.getString("result");
int i, j;
ArrayList categoriess, Ride;
if (result.equals("606")) {
JSONObject message = mainObj.getJSONObject("message");
categories = message.getJSONArray("categories");
ride_estimate = message.getJSONArray("ride_estimate");
// JSONArray ride_estimate = message.getJSONArray("ride_estimate");
for (i = 0; i < categories.length(); i++) {
Log.e("sushil", String.valueOf(i));
jsonObject = categories.getJSONObject(i);
id = jsonObject.getString("id");
display_name = jsonObject.getString("display_name");
image = jsonObject.getString("image");
eta = jsonObject.getString("eta");
Log.e("OutPut", id + " " + eta + " " + image + " " + amount_min + " " + amount_max);
}
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
}
}
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
Log.e("sushil ride_estimate", distance + " " + amount_min + " " + amount_max);
AdapterOlaUber adapterOlaUber = new AdapterOlaUber(context, arrayList, CabBookingActivity.this);
recyclerView.setAdapter(adapterOlaUber);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("pickup_lat", "" + pickLat);
params.put("pickup_lng", "" + pickLong);
params.put("drop_lat", String.valueOf(dropLat));
params.put("drop_lng", String.valueOf(dropLong));
params.put("category", "all");
params.put("token", token);
Log.e("sushil param", String.valueOf(params));
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
Here is my JSONRESPONSE
{
"result":"606",
"message":{
"categories":[
{
"id":"micro",
"display_name":"Micro",
"currency":"INR",
"distance_unit":"kilometre",
"time_unit":"minute",
"eta":5,
"distance":"0.7",
"ride_later_enabled":"true",
"image":"http:\/\/d1foexe15giopy.cloudfront.net\/micro.png",
"cancellation_policy":{
"cancellation_charge":50,
"currency":"INR",
"cancellation_charge_applies_after_time":5,
"time_unit":"minute"
},
"fare_breakup":[
{
"type":"flat_rate",
"minimum_distance":0,
"minimum_time":0,
"base_fare":50,
"minimum_fare":60,
"cost_per_distance":6,
"waiting_cost_per_minute":0,
"ride_cost_per_minute":1.5,
"surcharge":[
],
"rates_lower_than_usual":false,
"rates_higher_than_usual":false
}
]
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
],
"ride_estimate":[
{
"category":"prime_play",
"distance":3.99,
"travel_time_in_minutes":30,
"amount_min":155,
"amount_max":163,
"discounts":{
"discount_type":null,
"discount_code":null,
"discount_mode":null,
"discount":0,
"cashback":0
}
},
{ },
{ },
{ },
{ },
{ },
{ },
{ }
]
}
}
My Problem is that how can send the data in model.
My Model Should contain data Like id,displayName,amountMin,eta,image,amountMax
First of all you need to make two different models for category and ride_estimate.Because they both are in different loops. Also try this
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
}
May be this would helpful for you..
Thanks!
replace
eta = jsonObject.getString("eta");
by
int eta = jsonObject.getInt("eta");
On the basis of id of any cab type "prime" you can fetch image. what say
create some class as per your data
-----------------------------------com.example.CancellationPolicy.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CancellationPolicy {
#SerializedName("cancellation_charge")
#Expose
private Integer cancellationCharge;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("cancellation_charge_applies_after_time")
#Expose
private Integer cancellationChargeAppliesAfterTime;
#SerializedName("time_unit")
#Expose
private String timeUnit;
public Integer getCancellationCharge() {
return cancellationCharge;
}
public void setCancellationCharge(Integer cancellationCharge) {
this.cancellationCharge = cancellationCharge;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Integer getCancellationChargeAppliesAfterTime() {
return cancellationChargeAppliesAfterTime;
}
public void setCancellationChargeAppliesAfterTime(Integer cancellationChargeAppliesAfterTime) {
this.cancellationChargeAppliesAfterTime = cancellationChargeAppliesAfterTime;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
}
-----------------------------------com.example.Category.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Category {
#SerializedName("id")
#Expose
private String id;
#SerializedName("display_name")
#Expose
private String displayName;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("distance_unit")
#Expose
private String distanceUnit;
#SerializedName("time_unit")
#Expose
private String timeUnit;
#SerializedName("eta")
#Expose
private Integer eta;
#SerializedName("distance")
#Expose
private String distance;
#SerializedName("ride_later_enabled")
#Expose
private String rideLaterEnabled;
#SerializedName("image")
#Expose
private String image;
#SerializedName("cancellation_policy")
#Expose
private CancellationPolicy cancellationPolicy;
#SerializedName("fare_breakup")
#Expose
private List<FareBreakup> fareBreakup = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getDistanceUnit() {
return distanceUnit;
}
public void setDistanceUnit(String distanceUnit) {
this.distanceUnit = distanceUnit;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
public Integer getEta() {
return eta;
}
public void setEta(Integer eta) {
this.eta = eta;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getRideLaterEnabled() {
return rideLaterEnabled;
}
public void setRideLaterEnabled(String rideLaterEnabled) {
this.rideLaterEnabled = rideLaterEnabled;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public CancellationPolicy getCancellationPolicy() {
return cancellationPolicy;
}
public void setCancellationPolicy(CancellationPolicy cancellationPolicy) {
this.cancellationPolicy = cancellationPolicy;
}
public List<FareBreakup> getFareBreakup() {
return fareBreakup;
}
public void setFareBreakup(List<FareBreakup> fareBreakup) {
this.fareBreakup = fareBreakup;
}
}
-----------------------------------com.example.Discounts.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Discounts {
#SerializedName("discount_type")
#Expose
private Object discountType;
#SerializedName("discount_code")
#Expose
private Object discountCode;
#SerializedName("discount_mode")
#Expose
private Object discountMode;
#SerializedName("discount")
#Expose
private Integer discount;
#SerializedName("cashback")
#Expose
private Integer cashback;
public Object getDiscountType() {
return discountType;
}
public void setDiscountType(Object discountType) {
this.discountType = discountType;
}
public Object getDiscountCode() {
return discountCode;
}
public void setDiscountCode(Object discountCode) {
this.discountCode = discountCode;
}
public Object getDiscountMode() {
return discountMode;
}
public void setDiscountMode(Object discountMode) {
this.discountMode = discountMode;
}
public Integer getDiscount() {
return discount;
}
public void setDiscount(Integer discount) {
this.discount = discount;
}
public Integer getCashback() {
return cashback;
}
public void setCashback(Integer cashback) {
this.cashback = cashback;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("result")
#Expose
private String result;
#SerializedName("message")
#Expose
private Message message;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
}
-----------------------------------com.example.FareBreakup.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FareBreakup {
#SerializedName("type")
#Expose
private String type;
#SerializedName("minimum_distance")
#Expose
private Integer minimumDistance;
#SerializedName("minimum_time")
#Expose
private Integer minimumTime;
#SerializedName("base_fare")
#Expose
private Integer baseFare;
#SerializedName("minimum_fare")
#Expose
private Integer minimumFare;
#SerializedName("cost_per_distance")
#Expose
private Integer costPerDistance;
#SerializedName("waiting_cost_per_minute")
#Expose
private Integer waitingCostPerMinute;
#SerializedName("ride_cost_per_minute")
#Expose
private Double rideCostPerMinute;
#SerializedName("surcharge")
#Expose
private List<Object> surcharge = null;
#SerializedName("rates_lower_than_usual")
#Expose
private Boolean ratesLowerThanUsual;
#SerializedName("rates_higher_than_usual")
#Expose
private Boolean ratesHigherThanUsual;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getMinimumDistance() {
return minimumDistance;
}
public void setMinimumDistance(Integer minimumDistance) {
this.minimumDistance = minimumDistance;
}
public Integer getMinimumTime() {
return minimumTime;
}
public void setMinimumTime(Integer minimumTime) {
this.minimumTime = minimumTime;
}
public Integer getBaseFare() {
return baseFare;
}
public void setBaseFare(Integer baseFare) {
this.baseFare = baseFare;
}
public Integer getMinimumFare() {
return minimumFare;
}
public void setMinimumFare(Integer minimumFare) {
this.minimumFare = minimumFare;
}
public Integer getCostPerDistance() {
return costPerDistance;
}
public void setCostPerDistance(Integer costPerDistance) {
this.costPerDistance = costPerDistance;
}
public Integer getWaitingCostPerMinute() {
return waitingCostPerMinute;
}
public void setWaitingCostPerMinute(Integer waitingCostPerMinute) {
this.waitingCostPerMinute = waitingCostPerMinute;
}
public Double getRideCostPerMinute() {
return rideCostPerMinute;
}
public void setRideCostPerMinute(Double rideCostPerMinute) {
this.rideCostPerMinute = rideCostPerMinute;
}
public List<Object> getSurcharge() {
return surcharge;
}
public void setSurcharge(List<Object> surcharge) {
this.surcharge = surcharge;
}
public Boolean getRatesLowerThanUsual() {
return ratesLowerThanUsual;
}
public void setRatesLowerThanUsual(Boolean ratesLowerThanUsual) {
this.ratesLowerThanUsual = ratesLowerThanUsual;
}
public Boolean getRatesHigherThanUsual() {
return ratesHigherThanUsual;
}
public void setRatesHigherThanUsual(Boolean ratesHigherThanUsual) {
this.ratesHigherThanUsual = ratesHigherThanUsual;
}
}
-----------------------------------com.example.Message.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Message {
#SerializedName("categories")
#Expose
private List<Category> categories = null;
#SerializedName("ride_estimate")
#Expose
private List<RideEstimate> rideEstimate = null;
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<RideEstimate> getRideEstimate() {
return rideEstimate;
}
public void setRideEstimate(List<RideEstimate> rideEstimate) {
this.rideEstimate = rideEstimate;
}
}
-----------------------------------com.example.RideEstimate.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class RideEstimate {
#SerializedName("category")
#Expose
private String category;
#SerializedName("distance")
#Expose
private Double distance;
#SerializedName("travel_time_in_minutes")
#Expose
private Integer travelTimeInMinutes;
#SerializedName("amount_min")
#Expose
private Integer amountMin;
#SerializedName("amount_max")
#Expose
private Integer amountMax;
#SerializedName("discounts")
#Expose
private Discounts discounts;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Double getDistance() {
return distance;
}
public void setDistance(Double distance) {
this.distance = distance;
}
public Integer getTravelTimeInMinutes() {
return travelTimeInMinutes;
}
public void setTravelTimeInMinutes(Integer travelTimeInMinutes) {
this.travelTimeInMinutes = travelTimeInMinutes;
}
public Integer getAmountMin() {
return amountMin;
}
public void setAmountMin(Integer amountMin) {
this.amountMin = amountMin;
}
public Integer getAmountMax() {
return amountMax;
}
public void setAmountMax(Integer amountMax) {
this.amountMax = amountMax;
}
public Discounts getDiscounts() {
return discounts;
}
public void setDiscounts(Discounts discounts) {
this.discounts = discounts;
}
}
Now compile a library compile 'com.google.code.gson:gson:2.8.2'
then write few line to get your data fill in class
Gson gson = new Gson();
Example example = gson.fromJson(mainObj, Example.class);
Now you can try to fetch your categories like this
example.getCategories();
I have following JSON string that I need to set to the Java objects of POJO class.
What method should I follow?
{"status":"FOUND","messages":null,"sharedLists": [{"listId":"391647d","listName":"/???","numberOfItems":0,"colla borative":false,"displaySettings":true}] }
I tried using Gson but it did not work for me.
Gson gson = new Gson();
SharedLists target = gson.fromJson(sb.toString(), SharedLists.class);
Following is my SharedLists pojo
public class SharedLists {
#SerializedName("listId")
private String listId;
#SerializedName("listName")
private String listName;
#SerializedName("numberOfItems")
private int numberOfItems;
#SerializedName("collaborative")
private boolean collaborative;
#SerializedName("displaySettings")
private boolean displaySettings;
public int getNumberOfItems() {
return numberOfItems;
}
public void setNumberOfItems(int numberOfItems) {
this.numberOfItems = numberOfItems;
}
public boolean isCollaborative() {
return collaborative;
}
public void setCollaborative(boolean collaborative) {
this.collaborative = collaborative;
}
public boolean isDisplaySettings() {
return displaySettings;
}
public void setDisplaySettings(boolean displaySettings) {
this.displaySettings = displaySettings;
}
public String getListId() {
return listId;
}
public void setListId(String listId) {
this.listId = listId;
}
}
Following is your JSON string.
{
"status": "FOUND",
"messages": null,
"sharedLists": [
{
"listId": "391647d",
"listName": "/???",
"numberOfItems": 0,
"colla borative": false,
"displaySettings": true
}
]
}
Clearly sharedLists is a JSON array within the outer JSON object.
So I have two classes as follows (created from http://www.jsonschema2pojo.org/ by providing your JSON as input)
ResponseObject - Represents the outer object
public class ResponseObject {
#SerializedName("status")
#Expose
private String status;
#SerializedName("messages")
#Expose
private Object messages;
#SerializedName("sharedLists")
#Expose
private List<SharedList> sharedLists = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getMessages() {
return messages;
}
public void setMessages(Object messages) {
this.messages = messages;
}
public List<SharedList> getSharedLists() {
return sharedLists;
}
public void setSharedLists(List<SharedList> sharedLists) {
this.sharedLists = sharedLists;
}
}
and the SharedList - Represents each object within the array
public class SharedList {
#SerializedName("listId")
#Expose
private String listId;
#SerializedName("listName")
#Expose
private String listName;
#SerializedName("numberOfItems")
#Expose
private Integer numberOfItems;
#SerializedName("colla borative")
#Expose
private Boolean collaBorative;
#SerializedName("displaySettings")
#Expose
private Boolean displaySettings;
public String getListId() {
return listId;
}
public void setListId(String listId) {
this.listId = listId;
}
public String getListName() {
return listName;
}
public void setListName(String listName) {
this.listName = listName;
}
public Integer getNumberOfItems() {
return numberOfItems;
}
public void setNumberOfItems(Integer numberOfItems) {
this.numberOfItems = numberOfItems;
}
public Boolean getCollaBorative() {
return collaBorative;
}
public void setCollaBorative(Boolean collaBorative) {
this.collaBorative = collaBorative;
}
public Boolean getDisplaySettings() {
return displaySettings;
}
public void setDisplaySettings(Boolean displaySettings) {
this.displaySettings = displaySettings;
}
}
Now you can parse the entire JSON string with GSON as follows
Gson gson = new Gson();
ResponseObject target = gson.fromJson(inputString, ResponseObject.class);
Hope this helps.
I have json data regarding student details,That i want to print in respective textviews. i'm new to json services please help me to print the this data on screen.I'm using getters and setters for subject score so further i want to use them dynamically.
here is my json data
{
"studentInfo": {
"studentName": "srini#gmail.com",
"studentId": "abc",
"date": 14102017,
"JanuaryScoreCard" : {
"english" : "44",
"Science" : "45",
"maths": "66",
"social" : "56",
"hindi" : "67",
"kannada" : "78",
},
"MarchScoreCard" : {
" english " : "54",
" Science " : "56",
" maths ": "70",
" social " : "87",
" hindi " : "98",
" kannada " : "56"
},
"comments" : ""
}
I'm Something to print but could not,i don't where i'm going wrong
public void init()
{
try {
parseJSON();
} catch (JSONException e)
{
e.printStackTrace();
}
}
public void parseJSON() throws JSONException{
jsonObject = new JSONObject(strJson);
JSONObject object = jsonObject.getJSONObject("studentInfo");
patientName = object.getString("studentName");
patientID = object.getString("studentId");
mName.setText(studentName);
mUserId.setText(studentId);
}
You can use JSON parser and then you can print any data you want from that,
Use GSON for this, here is an example https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
Here is a basic JSON Parsing process
public void parseJson() {
String your_response = "replace this with your response";
try {
JSONObject jsonObject = new JSONObject(your_response);
JSONObject studentInfoJsonObject = jsonObject.getJSONObject("studentInfo");
StudentInfo studentInfo1 = new StudentInfo();
studentInfo1.setStudentName(studentInfoJsonObject.optString("studentName"));
studentInfo1.setStudentId(studentInfoJsonObject.optString("studentId"));
studentInfo1.setDate(studentInfoJsonObject.optString("date"));
studentInfo1.setComments(studentInfoJsonObject.optString("comments"));
JSONObject januaryScoreCardJsonObject = studentInfoJsonObject.optJSONObject("JanuaryScoreCard");
JanuaryScoreCard januaryScoreCard1 = new JanuaryScoreCard();
januaryScoreCard1.setEnglish(januaryScoreCardJsonObject.optString("english"));
januaryScoreCard1.setHindi(januaryScoreCardJsonObject.optString("hindi"));
januaryScoreCard1.setMaths(januaryScoreCardJsonObject.optString("maths"));
januaryScoreCard1.setSocial(januaryScoreCardJsonObject.optString("social"));
januaryScoreCard1.setKannada(januaryScoreCardJsonObject.optString("kannada"));
januaryScoreCard1.setScience(januaryScoreCardJsonObject.optString("Science"));
JSONObject marchScoreCardJsonObject = studentInfoJsonObject.optJSONObject("JanuaryScoreCard");
MarchScoreCard marchScoreCard = new MarchScoreCard();
marchScoreCard.setEnglish(marchScoreCardJsonObject.optString("english"));
marchScoreCard.setHindi(marchScoreCardJsonObject.optString("hindi"));
marchScoreCard.setMaths(marchScoreCardJsonObject.optString("maths"));
marchScoreCard.setSocial(marchScoreCardJsonObject.optString("social"));
marchScoreCard.setKannada(marchScoreCardJsonObject.optString("kannada"));
marchScoreCard.setScience(marchScoreCardJsonObject.optString("Science"));
studentInfo1.setJanuaryScoreCard(januaryScoreCard1);
studentInfo1.setMarchScoreCard(marchScoreCard);
} catch (JSONException e) {
e.printStackTrace();
}
}
Student Info Class
public class StudentInfo {
private String studentName;
private String studentId;
private String date;
private String comments;
private JanuaryScoreCard januaryScoreCard;
private MarchScoreCard marchScoreCard;
public JanuaryScoreCard getJanuaryScoreCard() {
return januaryScoreCard;
}
public void setJanuaryScoreCard(JanuaryScoreCard januaryScoreCard) {
this.januaryScoreCard = januaryScoreCard;
}
public MarchScoreCard getMarchScoreCard() {
return marchScoreCard;
}
public void setMarchScoreCard(MarchScoreCard marchScoreCard) {
this.marchScoreCard = marchScoreCard;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
and Here is January class
public class JanuaryScoreCard {
private String english;
private String Science;
private String maths;
private String kannada;
private String social;
private String hindi;
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
public String getScience() {
return Science;
}
public void setScience(String science) {
Science = science;
}
public String getMaths() {
return maths;
}
public void setMaths(String maths) {
this.maths = maths;
}
public String getKannada() {
return kannada;
}
public void setKannada(String kannada) {
this.kannada = kannada;
}
public String getSocial() {
return social;
}
public void setSocial(String social) {
this.social = social;
}
public String getHindi() {
return hindi;
}
public void setHindi(String hindi) {
this.hindi = hindi;
}
}
and Here is March Class
public class MarchScoreCard{
private String english;
private String Science;
private String maths;
private String kannada;
private String social;
private String hindi;
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
public String getScience() {
return Science;
}
public void setScience(String science) {
Science = science;
}
public String getMaths() {
return maths;
}
public void setMaths(String maths) {
this.maths = maths;
}
public String getKannada() {
return kannada;
}
public void setKannada(String kannada) {
this.kannada = kannada;
}
public String getSocial() {
return social;
}
public void setSocial(String social) {
this.social = social;
}
public String getHindi() {
return hindi;
}
public void setHindi(String hindi) {
this.hindi = hindi;
}
}
You need to parse this json Data , For this you need Create appropriate bean classes and put data while parsing json into this bean classes object and create List .
Then you need to create ListView and Adapter for populate data into Screen or Activity.