Deserializing enum using jackson - java

Spent some time figuring out what was the issue with deserializing but to no avail.
I am trying to read back from a JSON file that was created by the same class, Movie by the below code. But it is crashing on this said line of code.
List<Movie> myMovies = objectMapper.readValue(f,objectMapper.getTypeFactory().constructCollectionType(List.class, Movie.class));
A sample of the JSON file reads,
[
{
"movieID": 0,
"title": "asdad 1",
"type": "DIGITAL",
"synopsis": null,
"director": null,
"casts": [],
"status": "COMING SOON",
"showTimes": null,
"cinema": null,
"mRating": "G",
"rRating": 0,
"reviews": [],
"totalSales": 0
}
]
Here are the bunch of attribute declare on my Movie class
private int movieID;
private String title;
private MovieType type;
private String synopsis;
private String director;
private List<String> casts = new ArrayList<String>();
private MovieStatus status;
private List<ShowTime> showTimes;
private Cinema cinema;
private MovieRating mRating;
private ReviewersRating rRating;
private List<String> reviews = new ArrayList<String>();
private int totalSales;
stack trace
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token
at [Source: .\Database\Movies.json; line: 1, column: 81] (through reference chain: java.util.ArrayList[0]->entity.Movie["casts"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:857)
at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:62)
at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:520)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:258)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:125)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:245)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:217)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:25)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3736)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2658)
at entity.Movie.createMovie(Movie.java:166)
Examples of my enums to override the default JsonProperty
public enum ReviewersRating {
_0(0),_1(1), _2(2), _3(3), _4(4), _5(5);
private final int rating;
private ReviewersRating(final int rating) {
this.rating = rating;
}
#JsonValue
public int toInt()
{
return this.rating;
}
}
public enum MovieStatus {
#JsonProperty("COMING SOON")COMING_SOON, PREVIEW, #JsonProperty("NOW SHOWING")NOW_SHOWING, #JsonProperty("END OF SHOWING")END_OF_SHOWING;
}
public enum MovieRating {
G, PG, PG13, NC16, M18, R21;
}
public enum MovieType {
DIGITAL, #JsonProperty("3D")_3D, BLOCKBUSTER;
}
My Movie Class code. The writing in seems to work fine as I am able to produce the above JSON string. It is just the reading in that is having problem I guess?
import java.util.;
import java.io.;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Movie {
private int movieID;
private String title;
private MovieType type;
private String synopsis;
private String director;
private List<String> casts = new ArrayList<String>();
private MovieStatus status;
private List<ShowTime> showTimes;
private Cinema cinema;
private MovieRating mRating;
private ReviewersRating rRating;
private List<String> reviews = new ArrayList<String>();
private int totalSales;
public Movie() {
}
public Movie(String title, MovieType type, MovieRating mRating,
MovieStatus status) {
this.title = title;
this.type = type;
this.mRating = mRating;
this.status = status;
rRating = ReviewersRating._0;
}
public int getMovieID() {
return movieID;
}
public void setMovieID(int movieID) {
this.movieID = movieID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public MovieType getType() {
return type;
}
public void setType(MovieType type) {
this.type = type;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public List<String> getCasts() {
return casts;
}
public void setCasts(String cast) {
this.casts.add(cast);
}
public MovieStatus getStatus() {
return status;
}
public void setStatus(MovieStatus status) {
this.status = status;
}
public void addShowTime(ShowTime showTime) {
showTimes.add(showTime);
}
public void removeShowTime(ShowTime showTime) {
showTimes.remove(showTime);
}
public void setShowTimes(List<ShowTime> showTimes) {
this.showTimes = showTimes;
}
public List<ShowTime> getShowTimes() {
return showTimes;
}
public Cinema getCinema() {
return cinema;
}
public void setCinema(Cinema cinema) {
this.cinema = cinema;
}
public MovieRating getmRating() {
return mRating;
}
public void setmRating(MovieRating mRating) {
this.mRating = mRating;
}
public ReviewersRating getrRating() {
return rRating;
}
public void setrRating(ReviewersRating rRating) {
this.rRating = rRating;
}
public List<String> getReviews() {
return reviews;
}
public void setReviews(String reviews) {
this.reviews.add(reviews);
}
public float getTotalSales() {
return totalSales;
}
public void setTotalSales(int totalSales) {
this.totalSales = totalSales;
}
public void createMovie() {
ObjectMapper objectMapper = new ObjectMapper();
File f = new File("./Database/Movies.json");
if (f.exists() && !f.isDirectory()) { // if existing data exist, read
// from it and append new movie
// data
try
{
List<Movie> myMovies = objectMapper.readValue(f,objectMapper.getTypeFactory().constructCollectionType(List.class, Movie.class));
myMovies.add(this);
objectMapper.writeValue(new FileOutputStream(f), myMovies);
}
catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
try {
objectMapper.writeValue(new FileOutputStream(f), Collections.singleton(this));
}
catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Related

Retrofit with Gson Response.body() not working

I'am trying to parse data to a recyclerview, i had some problems about expecting JSONArray/JSONObject that i fixed with some help, but this moment I am a little bit lost in what to do in the Onresponse, the original - generatePhonesList(response.body()) isnt working.
this is my json and i am trying to parse the data inside the array results[] :
{
"success": true,
"metadata": {
"sort": "POPULARITY",
"total_products": 20,
"title": "Phones & Tablets",
"results": [
{
"sku": "1",
"name": "Samsung Galaxy S9",
"brand": "Samsung",
"max_saving_percentage": 30,
"price": 53996,
"special_price": 37990,
"image": "https://cdn2.gsmarena.com/vv/bigpic/samsung-galaxy-s9-.jpg",
"rating_average": 5
},
MainActivity (CALL and Recyclerview creation) :
GetPhoneDataService service = RetrofitInstance.getRetrofitInstance().create(GetPhoneDataService.class);
Call<APIReponse> call = service.getAllPhones();
call.enqueue(new Callback<APIReponse>() {
#Override
public void onResponse(Call<APIReponse> call, Response<APIReponse> response) {
generatePhonesList(response.body());
}
#Override
public void onFailure(Call<APIReponse> call, Throwable t) {
Log.e("eee" , "" + t.getMessage());
}
});
}
private void generatePhonesList(List<Result> phonesList){
recyclerView = findViewById(R.id.recyclerView);
adapter = new PhonesAdapter(phonesList,this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
this is the POJO Class's created in jsonschema2pojo :
public class APIReponse {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("metadata")
#Expose
private Metadata metadata;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
}
2 class
public class MetaData {
#SerializedName("sort")
#Expose
private String sort;
#SerializedName("total_products")
#Expose
private Integer totalProducts;
#SerializedName("title")
#Expose
private String title;
#SerializedName("results")
#Expose
private List<Result> results = null;
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public Integer getTotalProducts() {
return totalProducts;
}
public void setTotalProducts(Integer totalProducts) {
this.totalProducts = totalProducts;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
3 class:
public class Result {
#SerializedName("sku")
#Expose
private String sku;
#SerializedName("name")
#Expose
private String name;
#SerializedName("brand")
#Expose
private String brand;
#SerializedName("max_saving_percentage")
#Expose
private Integer maxSavingPercentage;
#SerializedName("price")
#Expose
private Integer price;
#SerializedName("special_price")
#Expose
private Integer specialPrice;
#SerializedName("image")
#Expose
private String image;
#SerializedName("rating_average")
#Expose
private Integer ratingAverage;
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getMaxSavingPercentage() {
return maxSavingPercentage;
}
public void setMaxSavingPercentage(Integer maxSavingPercentage) {
this.maxSavingPercentage = maxSavingPercentage;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getSpecialPrice() {
return specialPrice;
}
public void setSpecialPrice(Integer specialPrice) {
this.specialPrice = specialPrice;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getRatingAverage() {
return ratingAverage;
}
public void setRatingAverage(Integer ratingAverage) {
this.ratingAverage = ratingAverage;
}
}
You are passing the APIReponse model to the generatePhonesList(List<Result> phonesList) function. You need to pass only the list of results in this function.
Replace this:
generatePhonesList(response.body());
with:
generatePhonesList(response.body().getMetadata().getResults());
Here getMetadata() and getResults() are the getter functions of metadata model and List.
If you pay close attention response.body() will provide you with class APIResponse. But you need is List<Result>. To achieve this, try response.body().getMetadata().getResults()
This should give you the desired output.

Json Parser In android using local json file [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
Here is my Json data? how to parse in android
how to parse it
{
"data":[
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
]}
Google offers a very good json parser GSON.
Take a look here
Gson is a superb library for this. First generate the POJO for the json you have from jsonschematopojo. Here is the following POJO class:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class JsonResponse {
#SerializedName("data")
#Expose
private List<Datum> data = null;
public List<Datum> getData() {
return data;
}
public void setData(List<Datum> data) {
this.data = data;
}
public class Datum {
#SerializedName("widget")
#Expose
private Widget widget;
public Widget getWidget() {
return widget;
}
public void setWidget(Widget widget) {
this.widget = widget;
}
}
public class Image {
#SerializedName("src")
#Expose
private String src;
#SerializedName("name")
#Expose
private String name;
#SerializedName("hOffset")
#Expose
private int hOffset;
#SerializedName("vOffset")
#Expose
private int vOffset;
#SerializedName("alignment")
#Expose
private String alignment;
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHOffset() {
return hOffset;
}
public void setHOffset(int hOffset) {
this.hOffset = hOffset;
}
public int getVOffset() {
return vOffset;
}
public void setVOffset(int vOffset) {
this.vOffset = vOffset;
}
public String getAlignment() {
return alignment;
}
public void setAlignment(String alignment) {
this.alignment = alignment;
}
}
public class Text {
#SerializedName("data")
#Expose
private String data;
#SerializedName("size")
#Expose
private int size;
#SerializedName("style")
#Expose
private String style;
#SerializedName("name")
#Expose
private String name;
#SerializedName("hOffset")
#Expose
private int hOffset;
#SerializedName("vOffset")
#Expose
private int vOffset;
#SerializedName("alignment")
#Expose
private String alignment;
#SerializedName("onMouseUp")
#Expose
private String onMouseUp;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHOffset() {
return hOffset;
}
public void setHOffset(int hOffset) {
this.hOffset = hOffset;
}
public int getVOffset() {
return vOffset;
}
public void setVOffset(int vOffset) {
this.vOffset = vOffset;
}
public String getAlignment() {
return alignment;
}
public void setAlignment(String alignment) {
this.alignment = alignment;
}
public String getOnMouseUp() {
return onMouseUp;
}
public void setOnMouseUp(String onMouseUp) {
this.onMouseUp = onMouseUp;
}
}
public class Widget {
#SerializedName("debug")
#Expose
private String debug;
#SerializedName("window")
#Expose
private Window window;
#SerializedName("image")
#Expose
private Image image;
#SerializedName("text")
#Expose
private Text text;
public String getDebug() {
return debug;
}
public void setDebug(String debug) {
this.debug = debug;
}
public Window getWindow() {
return window;
}
public void setWindow(Window window) {
this.window = window;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public Text getText() {
return text;
}
public void setText(Text text) {
this.text = text;
}
}
public class Window {
#SerializedName("title")
#Expose
private String title;
#SerializedName("name")
#Expose
private String name;
#SerializedName("width")
#Expose
private int width;
#SerializedName("height")
#Expose
private int height;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
}
Now copy the entire json data and paste it in a String variable:
String jsonData="{\n" +
"\n" +
"\"data\":[ {\"widget\": { \"debug\": \"on\", \"window\": { \"title\": \"Sample Konfabulator Widget\", \"name\": \"main_window\", \"width\": 500, \"height\": 500 }, \"image\": { \"src\": \"Images/Sun.png\", \"name\": \"sun1\", \"hOffset\": 250, \"vOffset\": 250, \"alignment\": \"center\" }, \"text\": { \"data\": \"Click Here\", \"size\": 36, \"style\": \"bold\", \"name\": \"text1\", \"hOffset\": 250, \"vOffset\": 100, \"alignment\": \"center\", \"onMouseUp\": \"sun1.opacity = (sun1.opacity / 100) * 90;\" } }}\n" +
"\n" +
"]}"
Gson gson = new Gson();
JsonResponse jsonresp= gson.fromJson(jsonData, JsonResponse.class);
Now if you want to read from a file, then apply these codes:
public String mockDataReader(String fileName) {
try {
Path path = Paths.get(getClass().getClassLoader()
.getResource(fileName).toURI());
StringBuilder data = new StringBuilder();
Stream<String> lines = Files.lines(path);
lines.forEach((String line) -> data.append(line).append("\n"));
lines.close();
path = null;
return data.toString();
} catch (URISyntaxException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

How can I set My Json Value in Adapter

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

Unable to show json data from URL with java

I have a problem and I can't figure out how to solve it.
I have the following code:
public static void main(String[] args)
{
BufferedReader br = null;
StringBuilder sb = null;
String line = null;
Scanner scanner = new Scanner(System.in);
//print the menu
System.out.println("Choose from the menu:");
System.out.println("1 -> Town weather ");
System.out.println("2 -> About");
System.out.println("3 -> Exit");
try
{
//read from keyboard the value
//int choice = scanner.nextInt();
int choice = 1;
switch (choice)
{
case 1:
System.out.println("Give desired town:");
String town = str.nextLine();
URL json = new URL("http://api.openweathermap.org/data/2.5/weather?q=" + town + "&APPID=");
HttpURLConnection url = (HttpURLConnection) json.openConnection();
url.setRequestMethod("GET");
url.connect();
//read the data from url
br = new BufferedReader(new InputStreamReader(url.getInputStream()));
sb = new StringBuilder();
while ((line = br.readLine()) != null)
{
sb.append(line + '\n');
}
String txt = sb.toString();
break;
case 2:
break;
case 3:
System.exit(0);
}
}
catch (InputMismatchException i)
{
System.out.println("Wrong choice!");
}
catch (MalformedURLException m)
{
System.out.println("Wrong URL!");
}
catch (IOException io)
{
System.out.println("Wrong town! The url shows 404 not found");
}
catch (NullPointerException np)
{
System.out.println("Null exception!");
np.printStackTrace();
}
catch (Exception e) //catch all exception where not previous caught.
{
e.printStackTrace();
}
}
So I have the json data into txt variable. The problem is, that my project requires to show all the data (or a part of them), as a list. I must show them in such a way that a human can read them.
I tried pretty printing, but I do not want to show the symbols { } , :
Ideally, I would like to store these data into a database and then show some of them, while I maintain them. The first step, is to split them, in an array, only the strings and none of the special characters.
Can anyone help me with this? I searched stackoverflow, and I found many responses, but none worked for me.
EDIT: I updated the code, with my full main and below you can see the json response:
{
"coord": {
"lon": -86.97,
"lat": 34.8
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 270.48,
"pressure": 1033,
"humidity": 30,
"temp_min": 270.15,
"temp_max": 271.15
},
"visibility": 16093,
"wind": {
"speed": 2.6,
"deg": 340
},
"clouds": {
"all": 1
},
"dt": 1514921700,
"sys": {
"type": 1,
"id": 226,
"message": 0.0021,
"country": "US",
"sunrise": 1514897741,
"sunset": 1514933354
},
"id": 4830668,
"name": "Athens",
"cod": 200
}
Thank you in advance for your help.
Try below code to convert your response to json object,which you can convert to desired format or persist to DB later on
package test;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
String url="your URL"
DefaultHttpClient httpClient = new DefaultHttpClient();
httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//read response from body
ResponseHandler<String> handler = new BasicResponseHandler();
String respBody = handler.handleResponse(httpResponse);
if (respBody != null && !"".equals(respBody)) {
JsonObject responseJson = new
JsonParser().parse(respBody).getAsJsonObject();
}
}
}
I am not so sure what you mean by show "as a list". If I understand your question correctly, I think the best way to store and show the data is to be able to parse and cast the JSON data into a Java Object after you fetch the raw data from the response.
First step is to figure out what the JSON schema looks like and then extract/create a Java Object out of it. You can easily accomplish this using jar or lib or you can also do it do it online by copying and pasting the raw JSON into http://www.jsonschema2pojo.org/ and it will let you download a zip file that contains all the Java Objects needed for casting.
Once you have the Java Object in place, then you can use any JSON libaray to do the casting from and to the JSON to Java Object.
Here is a simple casting example using Gson library :
String txt = sb.toString();
Gson gson = new Gson();
Container jsonDataHolder = new Container();
try{
jsonDataHolder = gson.fromJson(txt , Container.class);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
// Finally don't forget to close BufferedReader.close()
// After Casting is completed, you can pretty much do anything with the object.
System.out.println("City Name : " + jsonDataHolder.getName())
// Below is the individual Java Object classes that are required to do the full scope casting of the JSON object you've provided.
public class Container {
#SerializedName("coord")
#Expose
private Coord coord;
#SerializedName("weather")
#Expose
private List<Weather> weather = null;
#SerializedName("base")
#Expose
private String base;
#SerializedName("main")
#Expose
private Main main;
#SerializedName("visibility")
#Expose
private Integer visibility;
#SerializedName("wind")
#Expose
private Wind wind;
#SerializedName("clouds")
#Expose
private Clouds clouds;
#SerializedName("dt")
#Expose
private Integer dt;
#SerializedName("sys")
#Expose
private Sys sys;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("cod")
#Expose
private Integer cod;
public Coord getCoord() {
return coord;
}
public void setCoord(Coord coord) {
this.coord = coord;
}
public List<Weather> getWeather() {
return weather;
}
public void setWeather(List<Weather> weather) {
this.weather = weather;
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public Integer getVisibility() {
return visibility;
}
public void setVisibility(Integer visibility) {
this.visibility = visibility;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public Integer getDt() {
return dt;
}
public void setDt(Integer dt) {
this.dt = dt;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCod() {
return cod;
}
public void setCod(Integer cod) {
this.cod = cod;
}
}
public class Coord {
#SerializedName("lon")
#Expose
private Double lon;
#SerializedName("lat")
#Expose
private Double lat;
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
}
public class Main {
#SerializedName("temp")
#Expose
private Double temp;
#SerializedName("pressure")
#Expose
private Integer pressure;
#SerializedName("humidity")
#Expose
private Integer humidity;
#SerializedName("temp_min")
#Expose
private Double tempMin;
#SerializedName("temp_max")
#Expose
private Double tempMax;
public Double getTemp() {
return temp;
}
public void setTemp(Double temp) {
this.temp = temp;
}
public Integer getPressure() {
return pressure;
}
public void setPressure(Integer pressure) {
this.pressure = pressure;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public Double getTempMin() {
return tempMin;
}
public void setTempMin(Double tempMin) {
this.tempMin = tempMin;
}
public Double getTempMax() {
return tempMax;
}
public void setTempMax(Double tempMax) {
this.tempMax = tempMax;
}
}
public class Wind {
#SerializedName("speed")
#Expose
private Double speed;
#SerializedName("deg")
#Expose
private Integer deg;
public Double getSpeed() {
return speed;
}
public void setSpeed(Double speed) {
this.speed = speed;
}
public Integer getDeg() {
return deg;
}
public void setDeg(Integer deg) {
this.deg = deg;
}
}
public class Clouds {
#SerializedName("all")
#Expose
private Integer all;
public Integer getAll() {
return all;
}
public void setAll(Integer all) {
this.all = all;
}
}
public class Sys {
#SerializedName("type")
#Expose
private Integer type;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("message")
#Expose
private Double message;
#SerializedName("country")
#Expose
private String country;
#SerializedName("sunrise")
#Expose
private Integer sunrise;
#SerializedName("sunset")
#Expose
private Integer sunset;
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Double getMessage() {
return message;
}
public void setMessage(Double message) {
this.message = message;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Integer getSunrise() {
return sunrise;
}
public void setSunrise(Integer sunrise) {
this.sunrise = sunrise;
}
public Integer getSunset() {
return sunset;
}
public void setSunset(Integer sunset) {
this.sunset = sunset;
}
}
Assumption:
The JSON Schema is the same for all the GET service call response.
Hope this helps my friend.

null values returning from gson.fromJson

I have some values in my object are returning by value null when converting from json to object and some others doesn't,i can't figure out why is that happening
here's my code to convert
OriginalMovie originalMovie = gson.fromJson(jsonString, OriginalMovie.class);
here's my json
{"page":1,
"results":[{"adult":false,
"backdrop_path":"/o4I5sHdjzs29hBWzHtS2MKD3JsM.jpg",
"genre_ids":[878,28,53,12],
"id":87101,"original_language":"en",
"original_title":"Terminator Genisys",
"overview":"The year is 2029. John Connor, leader of the resistance continues the war against the machines.",
"release_date":"2015-07-01",
"poster_path":"/5JU9ytZJyR3zmClGmVm9q4Geqbd.jpg",
"popularity":54.970301,
"title":"Terminator Genisys","video":false,
"vote_average":6.4,
"vote_count":197}],
"total_pages":11666,"total_results":233312}
and here's my base class (contains results)
package MovieReviewHelper;
import java.util.ArrayList;
import java.util.List;
public class OriginalMovie
{
private long page;
private List<Result> results = new ArrayList<Result>();
private long totalPages;
private long totalResults;
public long getPage()
{
return page;
}
public void setPage(long page)
{
this.page = page;
}
public List<Result> getResults()
{
return results;
}
public void setResults(List<Result> results)
{
this.results = results;
}
public long getTotalPages() {
return totalPages;
}
public void setTotalPages(long totalPages)
{
this.totalPages = totalPages;
}
public long getTotalResults()
{
return totalResults;
}
public void setTotalResults(long totalResults)
{
this.totalResults = totalResults;
}
}
and here's my other class
package MovieReviewHelper;
import java.util.ArrayList;
import java.util.List;
public class Result {
private boolean adult;
private String backdropPath;
private List<Long> genreIds = new ArrayList<Long>();
private long id;
private String originalLanguage;
private String originalTitle;
private String overview;
private String releaseDate;
private String posterPath;
private double popularity;
private String title;
private boolean video;
private double voteAverage;
private long voteCount;
public boolean isAdult()
{
return adult;
}
public void setAdult(boolean adult)
{
this.adult = adult;
}
public String getBackdropPath()
{
return backdropPath;
}
public void setBackdropPath(String backdropPath)
{
this.backdropPath = backdropPath;
}
public List<Long> getGenreIds()
{
return genreIds;
}
public void setGenreIds(List<Long> genreIds)
{
this.genreIds = genreIds;
}
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public String getOriginalLanguage()
{
return originalLanguage;
}
public void setOriginalLanguage(String originalLanguage)
{
this.originalLanguage = originalLanguage;
}
public String getOriginalTitle()
{
return originalTitle;
}
public void setOriginalTitle(String originalTitle)
{
this.originalTitle = originalTitle;
}
public String getOverview()
{
return overview;
}
public void setOverview(String overview)
{
this.overview = overview;
}
public String getReleaseDate()
{
return releaseDate;
}
public void setReleaseDate(String releaseDate)
{
this.releaseDate = releaseDate;
}
public String getPosterPath()
{
return posterPath;
}
public void setPosterPath(String posterPath)
{
this.posterPath = posterPath;
}
public double getPopularity()
{
return popularity;
}
public void setPopularity(double popularity)
{
this.popularity = popularity;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public boolean isVideo()
{
return video;
}
public void setVideo(boolean video)
{
this.video = video;
}
public double getVoteAverage()
{
return voteAverage;
}
public void setVoteAverage(double voteAverage)
{
this.voteAverage = voteAverage;
}
public long getVoteCount()
{
return voteCount;
}
public void setVoteCount(long voteCount)
{
this.voteCount = voteCount;
}
}
Your Json and Class variables should have the same name.
backdrop_path in Json and backdropPath in class would not work
Incase this helps for someone like me who spent half a day in trying to figure out a similar issue with gson.fromJson() returning object with null values, but when using #JsonProperty with an underscore in name and using Lombok in the model class.
My model class had a property like below and am using Lombok #Data for class
#JsonProperty(value="dsv_id")
private String dsvId;
So in my Json file I was using
"dsv_id"="123456"
Which was causing null value. The way I resolved it was changing the Json to have below ie.without the underscore. That fixed the problem for me.
"dsvId = "123456"

Categories

Resources