i have the following Json string, which I'm suppose to deserialize. The problem is: since this string comes from a server I can't change it and I need to deserialize as POJO. You can see that the Grafs keys have different values for each subarea. One is an object an the other an array. How can I handle this?
{
"Status": "true",
"Result: {
"rows": {
"row": {
"status": true,
"subareas": [
{
"nome": "Associacao Utente",
"id": 9,
"grafs": {
"rows": {
"id": 6,
"nome": "Associacao Utente",
"tipo": "PIE",
"serv": "MV_AS_UTENTE_POR_NEGOCIO",
"periodo": "ANO"
}
}
}, {
"nome": "Chaves",
"id": 60,
"grafs": {
"rows": [
{
"id": 35,
"nome": "Chaves Criados por ano",
"tipo": "LINHA",
"serv": "MV_ASSOC_TOTAL_CHAVES",
"periodo": "ANO"
}, {
"id": 592,
"nome": "Chaves Associado Ao User Portal",
"tipo": "BAR",
"serv": "MV_ASSOC_USER_CHAVES",
"periodo": "TODOS"
}, {
"id": 593,
"nome": "Chaves Associado Ao Negocios",
"tipo": "BAR",
"serv": "MV_ASSOC_CHAVES",
"periodo": "TODOS"
}
]
}
}
]
}
}
}
}
Here follows my classes.
public class Example {
private String Status;
private Result Result;
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
public Result getResult() {
return Result;
}
public void setResult(Result result) {
Result = result;
}
#Override
public String toString() {
return "Example [Status=" + Status + ", Result=" + Result + "]";
}
}
public class Result {
private Rows rows;
public Rows getRows() {
return rows;
}
public void setRows(Rows rows) {
this.rows = rows;
}
#Override
public String toString() {
return "Result [rows=" + rows + "]";
}
}
public class Grafs {
private List<Rows_> rows = new ArrayList<>();
public List<Rows_> getRows() {
return rows;
}
public void setRows(List<Rows_> Rows) {
this.rows = Rows;
}
#Override
public String toString() {
return "Grafs [rows=" + rows + "]";
}
}
public class Row {
private Boolean status;
private List<Subarea> subareas = new ArrayList<>();
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public List<Subarea> getSubareas() {
return subareas;
}
public void setSubareas(List<Subarea> subareas) {
this.subareas = subareas;
}
#Override
public String toString() {
return "Row [status=" + status + ", subareas=" + subareas + "]";
}
}
public class Row_ {
private Integer id;
private String nome;
private String serv;
private String periodo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getServ() {
return serv;
}
public void setServ(String serv) {
this.serv = serv;
}
public String getPeriodo() {
return periodo;
}
public void setPeriodo(String periodo) {
this.periodo = periodo;
}
#Override
public String toString() {
return "Row_ [id=" + id + ", nome=" + nome + ", serv=" + serv
+ ", periodo=" + periodo + "]";
}
}
public class Rows {
private Row row;
public Row getRow() {
return row;
}
public void setRow(Row row) {
this.row = row;
}
#Override
public String toString() {
return "Rows [row=" + row + "]";
}
}
public class Rows_ {
private Row_ row;
public Row_ getRow() {
return row;
}
public void setRow(Row_ row) {
this.row = row;
}
}
public class Subarea {
private String nome;
private Integer id;
private Grafs grafs;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Grafs getGrafs() {
return grafs;
}
public void setGrafs(Grafs grafs) {
this.grafs = grafs;
}
#Override
public String toString() {
return "Subarea [nome=" + nome + ", id=" + id + ", grafs=" + grafs
+ "]";
}
}
Using these classes I'm getting the following error:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 13 column 18.
I declared Rows_ as an arraylist and it encounters an object instead. But the second Rows_ is an array indeed. How can i address this?
Arrays with one element should still be rendered as arrays. That's why I used arrays. But it's giving the error I described.
Thanks for your help. I really appreciate it.
You can use TypeAdapterFactory to do the conversion. Here is a factory that will add that functionality to all of your List member types --
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
public class SingletonListTypeAdapterFactory implements TypeAdapterFactory {
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
Type type = typeToken.getType();
if (typeToken.getRawType() != List.class
|| !(type instanceof ParameterizedType)) {
return null;
}
Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
TypeAdapter<?> elementAdapter = gson.getAdapter(TypeToken.get(elementType));
TypeAdapter<T> arrayAdapter = gson.getDelegateAdapter(this, typeToken);
return (TypeAdapter<T>) newSingtonListAdapter((TypeAdapter<Object>) elementAdapter, (TypeAdapter<List<Object>>) arrayAdapter);
}
private <E> TypeAdapter<List<E>> newSingtonListAdapter(
final TypeAdapter<E> elementAdapter,
final TypeAdapter<List<E>> arrayAdapter) {
return new TypeAdapter<List<E>>() {
public void write(JsonWriter out, List<E> value) throws IOException {
if(value == null || value.isEmpty()) {
out.nullValue();
} else if(value.size() == 1) {
elementAdapter.write(out, value.get(0));
} else {
arrayAdapter.write(out, value);
}
}
public List<E> read(JsonReader in) throws IOException {
if (in.peek() != JsonToken.BEGIN_ARRAY) {
E obj = elementAdapter.read(in);
return Collections.singletonList(obj);
}
return arrayAdapter.read(in);
}
};
}
}
As bonus, it also serializes in the same way, if needed. If you also want to serialize as array, replace the write method with a call to arrayAdapter.write.
To you, add to your gson when building --
Gson gson = new GsonBuilder().registerTypeAdapterFactory(new SingletonListTypeAdapterFactory())
.create();
Related
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 this JSON data and I would like to deserialize it with Android to get it as an object to use in my class.
I get this folowing error :
Could not read JSON: Unrecognized field "card_details"
[
{
"id": "9",
"cat_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"app_id": "null",
"status": "1",
"lft": "1",
"rgt": "2",
"parent_cat_id": "0",
"added_date": "2017-01-12 12:41:29",
"last_edit_date": "2017-01-12 12:46:09",
"language_id": "0",
"category_id": "CAT-8584ce02f180b57a8c6d66570f696e02",
"name": "Sport",
"description": "This is sport category",
"image": "notitia/USR-70903638005256656/app-content/cat-img-da1161af03df255a989f8df5fc2e15bd.png",
"tags": "",
"custom_url": "sport",
"card_details": {
"nom_carte": "Pinacolada",
"prix": "5000",
"image": "notitia/USR-44043694343417880/app-content/e0fa7beb401e8fe77727f5a8241ff872.jpg",
"validity": "1"
}
}
]
Here is my AsyncTask to retrieve the data:
private class HttpRequestTaskCarte extends AsyncTask<Void,Void,Item[]> {
#Override
protected Item[] doInBackground(Void... params) {
try {
final String url = "http://domain.com/link.php?target=multi";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Item[] greeting = restTemplate.getForObject(url, Item[].class);
return greeting;
} catch (Exception e) {
//Toast.makeText(getActivity(), "Error Loading !", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
protected void onPreExecute(){
progressDialog = new ProgressDialog(getActivity(),
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("chargement des elements...");
progressDialog.show();
}
#Override
protected void onPostExecute(Item[] greeting) {
Log.d("okokok",""+greeting.length);
progressDialog.dismiss();
}
}
And here is the class that I am using to deserialize:
public class Item {
private List<card_details> carte;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCat_id() {
return cat_id;
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getApp_id() {
return app_id;
}
public void setApp_id(String app_id) {
this.app_id = app_id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLft() {
return lft;
}
public void setLft(String lft) {
this.lft = lft;
}
public String getRgt() {
return rgt;
}
public void setRgt(String rgt) {
this.rgt = rgt;
}
public String getParent_cat_id() {
return parent_cat_id;
}
public void setParent_cat_id(String parent_cat_id) {
this.parent_cat_id = parent_cat_id;
}
public String getAdded_date() {
return added_date;
}
public void setAdded_date(String added_date) {
this.added_date = added_date;
}
public String getLast_edit_date() {
return last_edit_date;
}
public void setLast_edit_date(String last_edit_date) {
this.last_edit_date = last_edit_date;
}
public String getLanguage_id() {
return language_id;
}
public void setLanguage_id(String language_id) {
this.language_id = language_id;
}
public String getCategory_id() {
return category_id;
}
public void setCategory_id(String category_id) {
this.category_id = category_id;
}
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 String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getCustom_url() {
return custom_url;
}
public void setCustom_url(String custom_url) {
this.custom_url = custom_url;
}
public List<Detail_cartes> getCarte() {
return carte;
}
public void setCarte(List<Detail_cartes> carte) {
this.carte = carte;
}
public static class Detail_cartes{
private String nom_carte ;
private String prix ;
private String image ;
private String validity ;
}
}
JSONArray array=new JSONArray(your data);
JSONObject obj=array.getJSONObject(0);
JSONObject cardDetail=obj.getJSONObject("card_details");
Hii u can use the following code:
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
I have the following JSON string, which I'm supposed to parse to POJO:
{
"Status": "true",
"Result": {
"rows": {
"row": {
"status": true,
"subareas": [
{
"nome": "Associacao Utente",
"id": 9,
"grafs": {
"rows": [
{
"id": 6,
"nome": "AssociacaoUtente",
"tipo": "PIE",
"serv": "MV_AS_UTENTE_POR_NEGOCIO",
"periodo": "ANO"
}
]
}
},
{
"nome": "Chaves",
"id": 60,
"grafs": {
"rows": [
{
"id": 35,
"nome": "ChavesCriadosporano",
"tipo": "LINHA",
"serv": "MV_ASSOC_TOTAL_CHAVES",
"periodo": "ANO"
},
{
"id": 592,
"nome": "ChavesAssociadoAoUserPortal",
"tipo": "BAR",
"serv": "MV_ASSOC_USER_CHAVES",
"periodo": "TODOS"
},
{
"id": 593,
"nome": "ChavesAssociadoAoNegocios",
"tipo": "BAR",
"serv": "MV_ASSOC_CHAVES",
"periodo": "TODOS"
}
]
}
}
]
}
}
}
}
and I have these classes to deserialize to POJO, which is working, thanks to Saurabh:
public class Example {
private String Status;
private Result Result;
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
public Result getResult() {
return Result;
}
public void setResult(Result result) {
Result = result;
}
#Override
public String toString() {
return "Example [Status=" + Status + ", Result=" + Result + "]";
}
}
public class Result {
private Rows rows;
public Rows getRows() {
return rows;
}
public void setRows(Rows rows) {
this.rows = rows;
}
#Override
public String toString() {
return "Result [rows=" + rows + "]";
}
}
public class Rows {
private Row row;
public Row getRow() {
return row;
}
public void setRow(Row row) {
this.row = row;
}
#Override
public String toString() {
return "Rows [row=" + row + "]";
}
}
import java.util.ArrayList;
import java.util.List;
public class Row {
private Boolean status;
private List<Subarea> subareas = new ArrayList<Subarea>();
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public List<Subarea> getSubareas() {
return subareas;
}
public void setSubareas(List<Subarea> subareas) {
this.subareas = subareas;
}
#Override
public String toString() {
return "Row [status=" + status + ", subareas=" + subareas + "]";
}
}
public class Subarea {
private String nome;
private Integer id;
private Grafs grafs;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Grafs getGrafs() {
return grafs;
}
public void setGrafs(Grafs grafs) {
this.grafs = grafs;
}
#Override
public String toString() {
return "Subarea [nome=" + nome + ", id=" + id + ", grafs=" + grafs
+ "]";
}
}
import java.util.ArrayList;
import java.util.List;
public class Grafs {
private List<Row_> rows = new ArrayList<Row_>();
public List<Row_> getRows() {
return rows;
}
public void setRows(List<Row_> rows) {
this.rows = rows;
}
#Override
public String toString() {
return "Grafs [rows=" + rows + "]";
}
}
public class Row_ {
private Integer id;
private String nome;
private String serv;
private String periodo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getServ() {
return serv;
}
public void setServ(String serv) {
this.serv = serv;
}
public String getPeriodo() {
return periodo;
}
public void setPeriodo(String periodo) {
this.periodo = periodo;
}
#Override
public String toString() {
return "Row_ [id=" + id + ", nome=" + nome + ", serv=" + serv
+ ", periodo=" + periodo + "]";
}
}
I need help populating the data received from JSON to a recyclerview, divided by sub areas. I'm confused on how to create the adapter.
First, your JSON should have Symmetry (See "grafs" key under "subareas" key) -
In first value it is as -
"grafs" : {
"rows" : {
"row" : {
And in second value it is as -
"grafs" : {
"rows" : [
So, I just made them correct as -
{
"Status": "true",
"Result": {
"rows": {
"row": {
"status": true,
"subareas": [
{
"nome": "Associacao Utente",
"id": 9,
"grafs": {
"rows": [
{
"id": 6,
"nome": "AssociacaoUtente",
"tipo": "PIE",
"serv": "MV_AS_UTENTE_POR_NEGOCIO",
"periodo": "ANO"
}
]
}
},
{
"nome": "Chaves",
"id": 60,
"grafs": {
"rows": [
{
"id": 35,
"nome": "ChavesCriadosporano",
"tipo": "LINHA",
"serv": "MV_ASSOC_TOTAL_CHAVES",
"periodo": "ANO"
},
{
"id": 592,
"nome": "ChavesAssociadoAoUserPortal",
"tipo": "BAR",
"serv": "MV_ASSOC_USER_CHAVES",
"periodo": "TODOS"
},
{
"id": 593,
"nome": "ChavesAssociadoAoNegocios",
"tipo": "BAR",
"serv": "MV_ASSOC_CHAVES",
"periodo": "TODOS"
}
]
}
}
]
}
}
}
}
Now you can create classes as -
Example.java
public class Example {
private String Status;
private Result Result;
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
public Result getResult() {
return Result;
}
public void setResult(Result result) {
Result = result;
}
#Override
public String toString() {
return "Example [Status=" + Status + ", Result=" + Result + "]";
}
}
Result.java
public class Result {
private Rows rows;
public Rows getRows() {
return rows;
}
public void setRows(Rows rows) {
this.rows = rows;
}
#Override
public String toString() {
return "Result [rows=" + rows + "]";
}
}
Rows.java
public class Rows {
private Row row;
public Row getRow() {
return row;
}
public void setRow(Row row) {
this.row = row;
}
#Override
public String toString() {
return "Rows [row=" + row + "]";
}
}
Row.java
import java.util.ArrayList;
import java.util.List;
public class Row {
private Boolean status;
private List<Subarea> subareas = new ArrayList<Subarea>();
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public List<Subarea> getSubareas() {
return subareas;
}
public void setSubareas(List<Subarea> subareas) {
this.subareas = subareas;
}
#Override
public String toString() {
return "Row [status=" + status + ", subareas=" + subareas + "]";
}
}
Subarea.java
public class Subarea {
private String nome;
private Integer id;
private Grafs grafs;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Grafs getGrafs() {
return grafs;
}
public void setGrafs(Grafs grafs) {
this.grafs = grafs;
}
#Override
public String toString() {
return "Subarea [nome=" + nome + ", id=" + id + ", grafs=" + grafs
+ "]";
}
}
Grafs.java
import java.util.ArrayList;
import java.util.List;
public class Grafs {
private List<Row_> rows = new ArrayList<Row_>();
public List<Row_> getRows() {
return rows;
}
public void setRows(List<Row_> rows) {
this.rows = rows;
}
#Override
public String toString() {
return "Grafs [rows=" + rows + "]";
}
}
Row_.java
public class Row_ {
private Integer id;
private String nome;
private String serv;
private String periodo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getServ() {
return serv;
}
public void setServ(String serv) {
this.serv = serv;
}
public String getPeriodo() {
return periodo;
}
public void setPeriodo(String periodo) {
this.periodo = periodo;
}
#Override
public String toString() {
return "Row_ [id=" + id + ", nome=" + nome + ", serv=" + serv
+ ", periodo=" + periodo + "]";
}
}
Now, you can test this as below -
Main.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.Example;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
/**
* #param args
*/
public static void main(String[] args) {
String j = "{\"Status\":\"true\",\"Result\":{\"rows\":{\"row\":{\"status\":true,\"subareas\":[{\"nome\":\"Associacao Utente\",\"id\":9,\"grafs\":{\"rows\":[{\"id\":6,\"nome\":\"AssociacaoUtente\",\"tipo\":\"PIE\",\"serv\":\"MV_AS_UTENTE_POR_NEGOCIO\",\"periodo\":\"ANO\"}]}},{\"nome\":\"Chaves\",\"id\":60,\"grafs\":{\"rows\":[{\"id\":35,\"nome\":\"ChavesCriadosporano\",\"tipo\":\"LINHA\",\"serv\":\"MV_ASSOC_TOTAL_CHAVES\",\"periodo\":\"ANO\"},{\"id\":592,\"nome\":\"ChavesAssociadoAoUserPortal\",\"tipo\":\"BAR\",\"serv\":\"MV_ASSOC_USER_CHAVES\",\"periodo\":\"TODOS\"},{\"id\":593,\"nome\":\"ChavesAssociadoAoNegocios\",\"tipo\":\"BAR\",\"serv\":\"MV_ASSOC_CHAVES\",\"periodo\":\"TODOS\"}]}}]}}}}";
Example r = gson.fromJson(j, Example.class);
System.out.println(r);
}
}
And the Result is -
Example [Status=true, Result=Result [rows=Rows [row=Row [status=true, subareas=[Subarea [nome=Associacao Utente, id=9, grafs=Grafs [rows=[Row_ [id=6, nome=AssociacaoUtente, serv=MV_AS_UTENTE_POR_NEGOCIO, periodo=ANO]]]], Subarea [nome=Chaves, id=60, grafs=Grafs [rows=[Row_ [id=35, nome=ChavesCriadosporano, serv=MV_ASSOC_TOTAL_CHAVES, periodo=ANO], Row_ [id=592, nome=ChavesAssociadoAoUserPortal, serv=MV_ASSOC_USER_CHAVES, periodo=TODOS], Row_ [id=593, nome=ChavesAssociadoAoNegocios, serv=MV_ASSOC_CHAVES, periodo=TODOS]]]]]]]]]
How can I get the GSON library to correctly convert the below JSON string to objects. I've tried for ages but it only seems to pick out the 2 "Word" objects and leave the member fields blank or null.
JSON:
{
"words": [
{
"Word": {
"id": "1",
"word": "submarine",
"word_syllables": "sub-mar-ine",
"picture": "none.jpg",
"soundfile": "",
"user_id": "1"
}
},
{
"Word": {
"id": "2",
"word": "computer",
"word_syllables": "com-pute-r",
"picture": "computer.jpg",
"soundfile": "",
"user_id": "0"
}
}
]
}
I thought that the above could be created simply by having a class called "Words" which contains an arraylist/list of Word objects.
The Words class;
package com.example.testgson.business;
import java.util.ArrayList;
import java.util.List;
import android.util.Log;
public class Words {
public List<Word> words=new ArrayList<Word>();
public Words(){
}
public int size(){
return words.size();
}
public void addWord(Word w){
this.words.add(w);
}
public List<Word> getWords() {
return words;
}
public void setWords(List<Word> words) {
this.words = words;
}
public void printAll(){
for(int i=0; i<words.size();i++){
Word w=(Word) words.get(i);
if(w!=null){
Log.d("word",w.getWord());
}
}
}
public List <Word> getWordList(){
return this.words;
}
}
The Word Class;
public class Word {
int id;
String word;
String word_syllables;
String picture;
String soundfile;
int user_id;
public Word(){
}
public Word(int id, String word, String word_syllables, String picture,
String soundfile, int user_id) {
super();
this.id = id;
this.word = word;
this.word_syllables = word_syllables;
this.picture = picture;
this.soundfile = soundfile;
this.user_id = user_id;
}
#Override
public String toString() {
return "Word [id=" + id + ", word=" + word + ", word_syllables="
+ word_syllables + ", picture=" + picture + ", soundfile="
+ soundfile + ", user_id=" + user_id + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getWord() {
return this.word;
}
public void setWord(String word) {
this.word = word;
}
public String getWord_syllables() {
return word_syllables;
}
public void setWord_syllables(String word_syllables) {
this.word_syllables = word_syllables;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getSoundfile() {
return soundfile;
}
public void setSoundfile(String soundfile) {
this.soundfile = soundfile;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
}
GSON convert code;
Gson gson = new Gson();
Words obj = gson.fromJson(sjson, Words.class);
You need to skip one level, because you array is not a List<Word> but a List<Holder> where the Holder class has a Word instance. You can either create this class, or write a custom deserializer to skip it:
class CustomDeserializer implements JsonDeserializer<Word> {
#Override
public Word deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException {
JsonElement content = je.getAsJsonObject().get("Word");
return new Gson().fromJson(content, type);
}
}
and then:
Gson gson = new GsonBuilder().registerTypeAdapter(Word.class, new CustomDeserializer()).create();
which yields:
Word [id=1, word=submarine, word_syllables=sub-mar-ine, picture=none.jpg, soundfile=, user_id=1]
Word [id=2, word=computer, word_syllables=com-pute-r, picture=computer.jpg, soundfile=, user_id=0]
I have been getting an error with DocumentReferences in a small JSF project i created to learn CouchDB/Ektorp .
I belive everything is working as is should in the CRUD, the id of the parent document is stored as a string, similar to the tutorial project.
But when I retrieve the parent object from the database I get this error:
org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type
[simple type, class com.pro.documents.Apple] from JSON String; no single-String
constructor/factory method (through reference chain: com.pro.documents.Eiere["apple"])
Here is the rest of the code:
{
"_id": "_design/Eiere",
"_rev": "17-ebb06b0d3102622a3d9849b9399cd94f",
"language": "javascript",
"views": {
"all": {
"map": "function(doc){if (doc.type == 'eiere') {emit(doc._id, doc);}}"
},
"ektorp_docrefs_apple": {
"map": "function(doc){ if(doc.eiere){emit([doc.eiere, 'apple', doc.kategori], null);}}"
}
}
}
{
"_id": "_design/Apple",
"_rev": "8-e04d8b5633776545b9eacdc998db4aea",
"language": "javascript",
"views": {
"all": {
"map": "function(doc){ if(doc.type == 'apple'){emit(doc._id, doc);}}"
}
}
}
public class Eiere extends CouchDbDocument {
#TypeDiscriminator
private String type;
private String navn;
private String telefon;
#DocumentReferences(backReference = "eiere", fetch = FetchType.LAZY, descendingSortOrder = true)
private Set<Apple> apple;
private Date dateCreated;
public Set<Apple> getApple() {
return apple;
}
public void setApple(Set<Apple> apples) {
this.apple = apples;
}
public void addApple(Apple c) {
Assert.notNull(c, "Apple may not be null");
if (getApple() == null) {
apple = new TreeSet<Apple>();
}
c.setEiere(this.getId());
apple.add(c);
}
public String getType() {
if (type == null) {
type = "eiere";
}
return type;
}
public void setType(String type) {
this.type = type;
}
public String getNavn() {
return navn;
}
public void setNavn(String navn) {
this.navn = navn;
}
public String getTelefon() {
return telefon;
}
public void setTelefon(String telefon) {
this.telefon = telefon;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
}
public class Apple extends CouchDbDocument implements Comparable<Apple>{
private static final long serialVersionUID = 1L;
#TypeDiscriminator
private String type;
private List<String> prices;
private String kategori;
private String eiere;
private Date dateCreated;
public String getType() {
if(type == null){
type = "apple";
}
return type;
}
public void setType(String type) {
this.type = type;
}
public List<String> getPrices() {
if(prices == null){
prices = new ArrayList<String>();
prices.add(0, " ");
prices.add(1, " ");
prices.add(2, " ");
}
return prices;
}
public void setPrices(List<String> prices) {
this.prices = prices;
}
public String getKategori() {
return kategori;
}
public void setKategori(String kategori) {
this.kategori = kategori;
}
public String getEiere() {
return eiere;
}
public void setEiere(String eiere) {
this.eiere = eiere;
}
#Override
public String toString() {
return prices.toString();
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
#Override
public int compareTo(Apple other) {
if (other == this) return 0;
if (dateCreated != null) {
return - dateCreated.compareTo(other.dateCreated);
}
return 0;
}
}
Any help or advice to help me understand what I'm doing wrong will be much appreciated.
Edit: If there is any information that I could add that would make my problem clearer or help in determining the cause of it please let me know.
Br.