Get value from dynamic json in Android - java

I want to parse this following dynamic JSON
{
"lowfares": {
"2017-07-30": {
"price": "1208.00",
"tax": "946.00",
"totalprice": "2154.00"
},
"2017-07-31": {
"price": "1208.00",
"tax": "946.00",
"totalprice": "2154.00"
}
}
}
This is my class contains price, tax, and totalprice
public class PriceModel {
#SerializedName("price")
private String price;
#SerializedName("tax")
private String tax;
#SerializedName("totalprice")
private String totalprice;
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getTax() {
return tax;
}
public void setTax(String tax) {
this.tax = tax;
}
public String getTotalPrice() {
return totalprice;
}
public void setTotalPrice(String totalPrice) {
this.totalprice = totalPrice;
}
}
This is my class to contain hashmap to store the response
public class ResponseModel {
#SerializedName("prices")
#Expose
private Map<String,PriceModel> priceModelMap;
public Map<String, PriceModel> getPriceModelMap() {
return priceModelMap;
}
public void setPriceModelMap(Map<String, PriceModel> priceModelMap) {
this.priceModelMap = priceModelMap;
}
}
in API interface, this is how I get the response
#GET("getprice/{start}/{end}/1/2")
Call<ResponseModel> getResponse(#Path("start") String start, #Path("end") String end);
and in MainActivity, I execute like this
Call call = apiInterface.getResponse("CRB","IMY");
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
Log.d("TAG",response.code()+" ");
Log.d("TAG","REsponse: "+response.body());
ResponseModel responseModel = (ResponseModel) response.body();
Log.d("TAG","REsponse: "+responseModel.getPriceModelMap());
Map<String, PriceModel> priceModelMap = responseModel.getPriceModelMap();
for (Map.Entry<String,PriceModel> entry : priceModelMap.entrySet()){
String key = entry.getKey();
PriceModel priceModel = entry.getValue();
System.out.println("KEY: "+key+" value: "+priceModel.getPrice());
}
}
#Override
public void onFailure(Call call, Throwable t) {
call.cancel();
}
});
I want to get price, tax, totalprice. But using my method, I tried getPrice method give null value.
How can I get the date and the values from that JSON? Thanks

So in the end I decided not to use retrofit as I couldnt find a way to parse the json as I wanted.
What I did to parse that dynamic json response
private HashMap<String,JSONObject> getLowfaresJson(JSONObject data){
HashMap<String,JSONObject> result = new HashMap<>();
try {
JSONObject lowfareJson = data.getJSONObject("lowfares");
Iterator keys = lowfareJson.keys();
while ((keys.hasNext())){
//Getting dynamic key from json
String currentDynamicKey = (String) keys.next();
//Getting dynamic value from json
JSONObject currentDynamicValue = lowfareJson.getJSONObject(currentDynamicKey);
result.put(currentDynamicKey,currentDynamicValue);
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
that method will return hashmap from dynamic json response. Hope this will help someone

You can simply gson.
Import in your project.
dependencies {
compile 'com.google.code.gson:gson:2.8.1'
}
public class TestModel {
private String name;
private int age;
private String position;
}
Use:
String strModel ="Staff{name='john', age=35, position='Developer'}"
Gson gson = new Gson();
TestModel testModel = gson.fromJson(strModel, TestModel .class);
Read more:Samples

Related

Deserializing json with GSON in Java

I have Json
{"0x3b198e26e473b8fab2085b37978e36c9de5d7f68":{"usd":541.56},"0x54523d5fb56803bac758e8b10b321748a77ae9e9":{"usd":0.059097},"0x330540a9d998442dcbc396165d3ddc5052077bb1":{"usd":1.649e-09}}
Next, I am using gson trying to convert json to price object
RequestEntity requestEntity = new RequestEntity(requestHeaders, HttpMethod.valueOf("GET"), uri);
restTemplate.exchange(requestEntity, String.class);
ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);
String response = responseEntity.getBody();
System.out.println(response);
Gson gson = new Gson();
Price price = gson.fromJson(response, Price.class);
Price.java
public class Price {
private Wallet wallet;
private Wallet token;
private Wallet contract;
public Wallet getWallet() {
return wallet;
}
public void setWallet(Wallet wallet) {
this.wallet = wallet;
}
public Wallet getToken() {
return token;
}
public void setToken(Wallet token) {
this.token = token;
}
public Wallet getContract() {
return contract;
}
public void setContract(Wallet contract) {
this.contract = contract;
}
}
Wallet.java
public class Wallet {
private Currencies currencies;
public Currencies getCurrencies() {
return currencies;
}
public void setCurrencies(Currencies currencies) {
this.currencies = currencies;
}
}
Currencies.java
public class Currencies {
String currency;
Integer value;
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
I need to name the class fields "0x3b198e26e473b8fab2085b37978e36c9de5d7f68", "0x54523d5fb56803bac758e8b10b321748a77ae9e9" and "0x330540a9d998442dcbc396165d3dbb150"? If so, these are not valid names.
Otherwise I get null when calling
System.out.println(price.getWallet());
I hope you can utilize custom deserializers here
register them for Gson like this:
GsonBuilder gsonBldr = new GsonBuilder();
gsonBldr.registerTypeAdapter(Price.class, new PriceCustomDeserializer());
gsonBldr.registerTypeAdapter(Wallet.class, new WalletCustomDeserializer());
gsonBldr.registerTypeAdapter(Currencies.class, new CurrenciesCustomDeserializer());
and deserializers implementation:
public class PriceCustomDeserializer implements JsonDeserializer<Price> {
#Override
public Price deserialize
(JsonElement jElement, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jObject = jElement.getAsJsonObject();
//parse 3 values (without names) from json by order
}
}
//add remaining 2 deserializers

Android: Use result from stringrequest in individual textviews

I have been able to get a string from an url, using volley. This string is now shown as one block in a textview. But I would like to be able to display this data in individual textviews. How could I do this?
Maybe important to know: I'm completely new at programming and this is my first week I'm doing this. So my method I used could be strange, and this might be a stupid question, but I'm just trying to learn, and to get the result I want.
This is the code I have now, to get the data from the url:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
textView.setText(response.toString());
Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
});
queue.add(request);
And this is how the result from the GET from the url looks like:
{"DeliveryDetailId":91003,"Delivery":{"DeliveryId":91,"DeliveryNumber":"1248","DropLocation":null,"DeliveryState":0},"ProductNumber":null,"Description":null,"PickLocation":"104","LocationCheck":null,"Quantity":64.0,"Histories":[],"BinNumberToUse":null}
So in this case I would like to have textviews which show the DeliveryID, Picklocation and Quantity. How can I extract this info from the string, so I can show it in the Textviews?
create model classes like below and store the response in Response.class
Then you can able to access DeliveryID by calling getDeliveryID()
-----------------------------------com.saranga.app.model.Delivery.java-----------------------------------
package com.saranga.app.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Delivery {
#SerializedName("DeliveryId")
#Expose
private Integer deliveryId;
#SerializedName("DeliveryNumber")
#Expose
private String deliveryNumber;
#SerializedName("DropLocation")
#Expose
private Object dropLocation;
#SerializedName("DeliveryState")
#Expose
private Integer deliveryState;
public Integer getDeliveryId() {
return deliveryId;
}
public void setDeliveryId(Integer deliveryId) {
this.deliveryId = deliveryId;
}
public String getDeliveryNumber() {
return deliveryNumber;
}
public void setDeliveryNumber(String deliveryNumber) {
this.deliveryNumber = deliveryNumber;
}
public Object getDropLocation() {
return dropLocation;
}
public void setDropLocation(Object dropLocation) {
this.dropLocation = dropLocation;
}
public Integer getDeliveryState() {
return deliveryState;
}
public void setDeliveryState(Integer deliveryState) {
this.deliveryState = deliveryState;
}
}
-----------------------------------com.saranga.app.model.Response.java-----------------------------------
package com.saranga.app.model;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Response {
#SerializedName("DeliveryDetailId")
#Expose
private Integer deliveryDetailId;
#SerializedName("Delivery")
#Expose
private Delivery delivery;
#SerializedName("ProductNumber")
#Expose
private Object productNumber;
#SerializedName("Description")
#Expose
private Object description;
#SerializedName("PickLocation")
#Expose
private String pickLocation;
#SerializedName("LocationCheck")
#Expose
private Object locationCheck;
#SerializedName("Quantity")
#Expose
private Double quantity;
#SerializedName("Histories")
#Expose
private List<Object> histories = null;
#SerializedName("BinNumberToUse")
#Expose
private Object binNumberToUse;
public Integer getDeliveryDetailId() {
return deliveryDetailId;
}
public void setDeliveryDetailId(Integer deliveryDetailId) {
this.deliveryDetailId = deliveryDetailId;
}
public Delivery getDelivery() {
return delivery;
}
public void setDelivery(Delivery delivery) {
this.delivery = delivery;
}
public Object getProductNumber() {
return productNumber;
}
public void setProductNumber(Object productNumber) {
this.productNumber = productNumber;
}
public Object getDescription() {
return description;
}
public void setDescription(Object description) {
this.description = description;
}
public String getPickLocation() {
return pickLocation;
}
public void setPickLocation(String pickLocation) {
this.pickLocation = pickLocation;
}
public Object getLocationCheck() {
return locationCheck;
}
public void setLocationCheck(Object locationCheck) {
this.locationCheck = locationCheck;
}
public Double getQuantity() {
return quantity;
}
public void setQuantity(Double quantity) {
this.quantity = quantity;
}
public List<Object> getHistories() {
return histories;
}
public void setHistories(List<Object> histories) {
this.histories = histories;
}
public Object getBinNumberToUse() {
return binNumberToUse;
}
public void setBinNumberToUse(Object binNumberToUse) {
this.binNumberToUse = binNumberToUse;
}
}
You need to decode your JSONObject and individually get each element unless it's in a JSONArray in that case you need to loop through it
#Override
public void onResponse(String response) {
JSONObject json = new JSONObject(response);
textView.setText(json.getString("DeliveryDetailld"));
JSONObject details = json.getJSONObject("Delivery");
//Get data in Delivery Object
textView2.setText(details.getString("DeliveryId"));
}

How do I POST a JSON array and get a JSON object in response using preferably android Volley?

The API I need to post to needs a JSONArray but is responding with a JSONObject. Unfortunately from what I can tell the Android Volley library has no method for this.
Is there a way to write a custom request and how would this be done to do what I explained above?
If it can not be done with Volley, how would you suggest I do it?
The method would look like this I believe:
//The array:
JSONArray itemArray = new JSONArray();
try {
for (MenuItem menuItem : listOfItems) {
JSONObject item = new JSONObject();
Log.d(LOG_TAG, "Item ID--> " + menuItem.getId());
Log.d(LOG_TAG, "Item Quantity--> " + menuItem.getNumOrdered());
Log.d(LOG_TAG, "Item Price Lvl--> " +
menuItem.getPrice_levels().get(0).getId().toString());
Log.d(LOG_TAG, "Item Comments--> " +
menuItem.getSpecialInstructions());
item.put("menu_item", menuItem.getId());
item.put("quantity", menuItem.getNumOrdered());
item.put("price_level",
menuItem.getPrice_levels().get(0).getId().toString());
item.put("comment", menuItem.getSpecialInstructions());
JSONArray discounts = new JSONArray();
JSONObject discount = new JSONObject();
discount.put("discount", null);
item.put("discounts", discounts);
JSONArray modifiers = new JSONArray();
JSONObject modifier = new JSONObject();
modifier.put("modifier",
menuItem.getModifierGroups().get(0).getId());
item.put("modifiers", modifiers);
itemArray.put(item);
}
//The volley request
JsonArrayRequest jsArrayRequest = new JsonArrayRequest(Request.Method.POST,
url, itemArray, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
finalized();
} catch (Exception e) {
Log.v("volley ex", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("volley error", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Api-Key", "api key");
headers.put("Content-Type", "application/json");
return headers;
}
};
requestQueue.add(jsArrayRequest);
}
//The menuitem class
package com.garcon.garcon;
import java.io.Serializable;
import java.util.ArrayList;
public class MenuItem implements Serializable {
public String id;
public String name;
public Integer price;
protected ArrayList<PriceLevel> price_levels;
protected Boolean in_stock;
protected int modifier_groups_count;
protected ArrayList<ModifierGroup> mGroups;
//not defined in API but will give Category's ID to MenuItem
protected String categoryID;
//user defined variable
public int numOrdered = 0;
private String specialInstructions = "";
//http://stackoverflow.com/questions/18814076/how-to-make-intellij-show-
//eclipse-like-api-documentation-on-mouse-hover
/**
* Complete constructor for MenuItem.
*
* #param id The menu item’s id as stored in the POS. Sometimes a compound
value derived from other data
* #param name The name of the Menu Item as stored in the POS
* #param price The price, in cents
* #param price_levels Array of Hashes (id String Price Level Identifier,
price Integer The price of the menu item at this price level, in cents)
* #param in_stock Whether or not the item is currently available for order.
* #param mGroups Modifier Groups associated with the Menu Item.
* #param modifier_groups_count The number of Modifier Groups associated
with the Menu Item.
* #param categoryID parent category's id NOT name
*/
public MenuItem(String id, String name, Integer price, ArrayList<PriceLevel>
price_levels,
Boolean in_stock, ArrayList<ModifierGroup> mGroups, Integer
modifier_groups_count, String categoryID){
this.id = id;
this.name = name;
this.price = price;
this.price_levels = price_levels;
this.in_stock = in_stock;
this.mGroups = mGroups;
this.modifier_groups_count = modifier_groups_count;
this.categoryID = categoryID;
}
public ArrayList<PriceLevel> getPrice_levels() {
return price_levels;
}
public void setPrice_levels(ArrayList<PriceLevel> price_levels) {
this.price_levels = price_levels;
}
public String getId() {
return id;
}
public String getName(){
return name;
}
String getCategoryID() {
return categoryID;
}
public Integer getPrice(){
return this.price;
}
ArrayList<ModifierGroup> getModifierGroups(){ return this.mGroups;}
int getNumOrdered(){return this.numOrdered;}
void setNumOrdered(int amount){
numOrdered = amount;
}
String getSpecialInstructions(){return this.specialInstructions;}
void setSpecialInstructions(String instructions){
specialInstructions = instructions;
}
static class ModifierGroup implements Serializable{
private String id, name;
private Integer minimum, maximum;
private boolean required;
private ArrayList<ItemModifier> modifier_list;
public ModifierGroup(String id, String name, int minimum, int maximum,
boolean required, ArrayList<ItemModifier> modifier_list){
this.id = id;
this.name = name;
this.minimum = minimum;
this.maximum = maximum;
this.required = required;
this.modifier_list = modifier_list;
}
public ModifierGroup(){}
String getId(){return id;}
String getName(){return name;}
Integer getMinimum(){return minimum;}
Integer getMaximum(){return maximum;}
boolean isRequired(){return required;}
ArrayList<ItemModifier> getModifierList(){ return
this.modifier_list;}
static class ItemModifier implements Serializable{
private String id, name;
private Integer price_per_unit;
private ArrayList<PriceLevel> priceLevelsList;
//user defined variable
private boolean added = false;
public ItemModifier(String id, String name, Integer
price_per_unit, ArrayList<PriceLevel> priceLevelsList){
this.id = id;
this.name = name;
this.price_per_unit = price_per_unit;
this.priceLevelsList = priceLevelsList;
}
String getId(){return id;}
String getName(){return name;}
Integer getPricePerUnit(){return price_per_unit;}
ArrayList<PriceLevel> getPriceLevelsList(){return
priceLevelsList;}
boolean isAdded(){ return added;}
void setAdded(boolean b){added = b;}
}
static class ItemModifierGrouped extends ItemModifier implements
Serializable{
private int group_id;
public ItemModifierGrouped(String id, String name, Integer
price_per_unit, ArrayList<PriceLevel> priceLevelsList, int
group_id){
super(id,name,price_per_unit,priceLevelsList);
this.group_id = group_id;
}
}
}
public static class PriceLevel implements Serializable{
public String id;
public Integer price;
public PriceLevel(){}
public PriceLevel(String id, Integer price){
this.id = id;
this.price = price;
}
public String getId(){return id;}
public Integer getPrice(){return price;}
}
}
try this
final String httpUrl = url;
Log.i(TAG,httpUrl.toString());
try{
JSONArray parametersForPhp = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put(key,"0");
jsonObject.put("key","");
jsonObject.put(key,sharedPreferences.getString(PATIENT_ID,BLANK));
jsonObject.put(APP_LANGUAGE,sharedPreferences.getString(APP_LANGUAGE,BLANK));
parametersForPhp.put(jsonObject);
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, httpUrl, parametersForPhp,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.i(TAG,response.toString());
if (response==null){
Toast.makeText(getApplicationContext(),"Please Try Again!",Toast.LENGTH_SHORT).show();
}else {
try {
//you code
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueueSingleton.getInstance(getApplicationContext()).addToRequestQueue(arrayRequest);
}catch (Exception e){
e.printStackTrace();
}

Unable to parse JSON with Jackson (mapping doesn't work)

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();

Android Studio - Issue loading JSON

I'm using Android Studio and I want to make a listview, which contains values that are received by JSON.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String JSONString = Handler.makeServiceCall(JSONUrl);
Log.e(TAG, "Response:" + JSONString);
if(JSONString != null){
try {
JSONObject CountriesJSONObject = new JSONObject(JSONString);
JSONArray Countries = CountriesJSONObject.getJSONArray("countries");
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i);
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
} catch (final JSONException e){
Log.e(TAG,e.getMessage());
ProgressDialog.setMessage("Error loading Data!");
}
}
return null;
}
This is the code for getting the JSON values, and i'm receiving an error
"No value for id"
What am I doing wrong?
You still have the "country" key to unwrap. Try like this:
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i).getJSONObject("country");
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
First step is to create a new Java class model for the JSON - you can just copy and paste this.
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
public class Countries {
public class CountriesList implements Serializable {
private Country[] countries;
public Country[] getCountries() {
return countries;
}
public void setCountries(Country[] countries) {
this.countries = countries;
}
public ArrayList<Country> getCountriesAsList() {
if(countries == null || countries.length == 0) {
return new ArrayList<>();
} else {
return (ArrayList<Country>) Arrays.asList(countries);
}
}
}
public class Country implements Serializable {
private String id;
private String name;
private String image;
public Country() {
}
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 getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
}
Now, it's simply converting the JSON into Java object like this. You can use that ArrayList for adapter or however you like.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String jsonString = Handler.makeServiceCall(JSONUrl);
Countries.CountriesList countries = new Gson().fromJson(jsonString, Countries.CountriesList.class);
// this is the full list of all your countries form json
ArrayList<Countries.Country> countryList = countries.getCountriesAsList();
}
Note: you will need the Gson library to use the solution I showed above. I use that to convert JSON into Java object.
compile 'com.google.code.gson:gson:2.8.0'

Categories

Resources