I'm trying to make a simple weather app. I'm using this API for it. on that same page is a list of parameters in the JSON response. I can search for all the parameters and get a response except for the 'weather' parameter. every time I try that I get an
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3 path $[0]
error. I'm not sure what's causing it. here's my code.
public class Weather {
private String city;
private OWM owm = new OWM("8984d739fa91d7031fff0e84a3d2c520");
private CurrentWeather currentWeather;
private String weather;
private Clouds cloud;
public Weather() throws APIException {
String API_KEY = "8984d739fa91d7031fff0e84a3d2c520";
String Location = "Brooklyn";
String urlString = "http://api.openweathermap.org/data/2.5/weather?q=" + Location
+ "&appid=" + API_KEY + "&units=imperial";
try {
StringBuilder result = new StringBuilder();
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null){
result.append(line);
}
rd.close();
System.out.println(result);
Map<String, Object> respMap = jsonToMap(result.toString());
Map<String, Object> mainMap = jsonToMap(respMap.get("main").toString());
Map<String, Object> windMap = jsonToMap(respMap.get("wind").toString());
Map<String, Object> cloudsMap = jsonToMap(respMap.get("weather").toString());
// error is here
System.out.println("Current Temperature: " + mainMap.get("temp"));
System.out.println("current humidity " + mainMap.get("humidity"));
System.out.println("clouds " + respMap.get("description"));
// System.out.println("weather conditions: " + cloudsMap.get("main"));
// this always returns null
System.out.println("wind speeds " + windMap.get("speed"));
System.out.println("wind angle: " + windMap.get("deg"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Map<String, Object> jsonToMap(String str){
Map<String, Object> map = new Gson().fromJson(
str, new TypeToken<HashMap<String, Object>>() {}.getType()
);
return map;
}
public String getCityName() {
return cityName;
}
public int getCurrentWeather() throws APIException {
owm.setUnit(OWM.Unit.IMPERIAL);
currentWeather = owm.currentWeatherByCityName(this.cityName);
return (int) Math.round(currentWeather.getMainData().getTemp());
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public void setZipCode(String zipCode){
this.zipCode = zipCode;
}
public String getZipCode(){
return this.zipCode;
}
public String getWeather(){
return this.weather;
}
}
I'm not really sure why that one parameter isn't working. I can search anything else fine, so why can't I search the weather parameter?
Edit:
I'm doing this in my try/catch statement. it's giving me a NullPointerException
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.connect();
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) conn.getContent()));
JsonObject rootObj = root.getAsJsonObject();
String description = rootObj.get("weather").getAsString();
// name of the array in the json
System.out.println(description);
Instead of blindly considering Hashmap for keyvalues, consider creating pojos, and then parse it.
Create all PoJo for json.
Main.java
public class Weather {
public static void main(String[] args) {
String API_KEY = "8984d739fa91d7031fff0e84a3d2c520";
String Location = "Brooklyn";
String urlString = "http://api.openweathermap.org/data/2.5/weather?q=" + Location
+ "&appid=" + API_KEY + "&units=imperial";
try {
StringBuilder result = new StringBuilder();
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null){
result.append(line);
}
rd.close();
System.out.println(result);
com.google.gson.Gson gson=new Gson();
Example finalResult=gson.fromJson(result.toString() , Example.class);
System.out.println(finalResult.getMain().getTemp()); //56.26
System.out.println(finalResult.getMain().getHumidity()); // 54
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Example.java (This pojo is for your json schema)
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#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("timezone")
#Expose
private Integer timezone;
#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 getTimezone() {
return timezone;
}
public void setTimezone(Integer timezone) {
this.timezone = timezone;
}
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;
}
}
Coord.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
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;
}
}
Weather.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Weather {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("main")
#Expose
private String main;
#SerializedName("description")
#Expose
private String description;
#SerializedName("icon")
#Expose
private String icon;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
Main.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
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 Integer 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 Integer getTempMin() {
return tempMin;
}
public void setTempMin(Integer tempMin) {
this.tempMin = tempMin;
}
public Double getTempMax() {
return tempMax;
}
public void setTempMax(Double tempMax) {
this.tempMax = tempMax;
}
}
Wind.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
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;
}
}
Clouds.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Clouds {
#SerializedName("all")
#Expose
private Integer all;
public Integer getAll() {
return all;
}
public void setAll(Integer all) {
this.all = all;
}
}
Sys.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
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;
}
}
Map<String, Object> cloudsMap = jsonToMap(respMap.get("weather").toString());
This is the problem. You're trying to parse the weather property of the response as an object (a Map) but it's actually an array.
The best way to parse the Json here is Gson Library
Here first you can create pojo class of response you getting ,after that just pass the response String and get your output.
Gson gson=new Gson();
YourClass result=gson.fromjson(jsonString , YourClass.class);
Related
I am trying to parse a JSON string to Java object.
The JSON string is as follows :
{
"token":"Hn2jqNYe75dOY5Xj2BmZTLAB",
"team_id":"T394M2RS5",
"api_app_id":"AC1UE8Y4C",
"event":{
"type":"message",
"user":"UC1C1D059",
"text":"test",
"client_msg_id":"bf824b77-c2ff-4cf3-b770-278168d006fb",
"ts":"1533637676.000135",
"channel":"DC2A6V4SZ",
"event_ts":"1533637676.000135",
"channel_type":"app_home"
},
"type":"event_callback",
"authed_teams":[
"T394M2RS5"
],
"event_id":"EvC5BPR1N2",
"event_time":1533637676
}
I am using GSON to make the conversion, but i don't know how to
design the Java class, because the JSON contains another object( the event object).
Any suggestion how to make the conversion?
Thanks in advance.
Try to follow documentation. It helps you to convert a JSON to a Java Class.
Data conversions:
JSON Object - Java class
Array - List<>
Helpful links:
This is the library you need to include (tutorials included) in Java: GSON Converter Git
This is a weather sample of a JSON (example by coordinates): JSON example website
This is an JSON to Class online converter: Jsonschema2pojo generator
You can use jsonschema2pojo to convert the JSON to classes like this:
-----------------------------------com.example.Clouds.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Clouds {
#SerializedName("all")
#Expose
private Integer all;
public Integer getAll() {
return all;
}
public void setAll(Integer all) {
this.all = all;
}
}
-----------------------------------com.example.Coord.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Coord {
#SerializedName("lon")
#Expose
private Integer lon;
#SerializedName("lat")
#Expose
private Integer lat;
public Integer getLon() {
return lon;
}
public void setLon(Integer lon) {
this.lon = lon;
}
public Integer getLat() {
return lat;
}
public void setLat(Integer lat) {
this.lat = lat;
}
}
-----------------------------------com.example.Data.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Data {
#SerializedName("coord")
#Expose
private Coord coord;
#SerializedName("sys")
#Expose
private Sys sys;
#SerializedName("weather")
#Expose
private List<Weather> weather = null;
#SerializedName("main")
#Expose
private Main main;
#SerializedName("wind")
#Expose
private Wind wind;
#SerializedName("rain")
#Expose
private Rain rain;
#SerializedName("clouds")
#Expose
private Clouds clouds;
#SerializedName("dt")
#Expose
private Integer dt;
#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 Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public List<Weather> getWeather() {
return weather;
}
public void setWeather(List<Weather> weather) {
this.weather = weather;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Rain getRain() {
return rain;
}
public void setRain(Rain rain) {
this.rain = rain;
}
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 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;
}
}
-----------------------------------com.example.Main.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Main {
#SerializedName("temp")
#Expose
private Double temp;
#SerializedName("humidity")
#Expose
private Integer humidity;
#SerializedName("pressure")
#Expose
private Integer pressure;
#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 getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public Integer getPressure() {
return pressure;
}
public void setPressure(Integer pressure) {
this.pressure = pressure;
}
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;
}
}
-----------------------------------com.example.Rain.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Rain {
#SerializedName("3h")
#Expose
private Integer _3h;
public Integer get3h() {
return _3h;
}
public void set3h(Integer _3h) {
this._3h = _3h;
}
}
-----------------------------------com.example.Sys.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Sys {
#SerializedName("country")
#Expose
private String country;
#SerializedName("sunrise")
#Expose
private Integer sunrise;
#SerializedName("sunset")
#Expose
private Integer sunset;
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;
}
}
-----------------------------------com.example.Weather.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Weather {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("main")
#Expose
private String main;
#SerializedName("description")
#Expose
private String description;
#SerializedName("icon")
#Expose
private String icon;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
-----------------------------------com.example.Wind.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Wind {
#SerializedName("speed")
#Expose
private Double speed;
#SerializedName("deg")
#Expose
private Double deg;
public Double getSpeed() {
return speed;
}
public void setSpeed(Double speed) {
this.speed = speed;
}
public Double getDeg() {
return deg;
}
public void setDeg(Double deg) {
this.deg = deg;
}
}
After all is done you can do something like this in Java:
String config_settings = "Your JSON String";
Gson converter = new Gson();
ConfigSettings settings = converter.fromJson(config_settings , Data.class);
This is pretty straightforward:
Map each JSON key to a POJO attribute
Use #SerializedName to customize JSON key
Map nested JSON object to a class
Map [] to array
Map {} to object
And this is your result:
public class YourClass {
private String token;
#SerializedName("team_id"
private String teamId;
#SerializedName("api_app_id")
private String apiAppId;
private Event event;
private String type;
#SerializedName("authed_teams")
private List<String> authedTeams;
.
.
.
}
private class Event {
private String type;
.
.
.
#SerializedName("event_ts")
private string eventTs;
#SerializedName("channel_type")
private String channelType;
}
for GSON Library, you can create a package of classes that is identical to your JSON structure, for this, you can use http://www.jsonschema2pojo.org/ and you can use the
.fromJson() method, to transfer the JSON content to the container class.
Another thing is, you can transfer your JSON to Java Map class instead of creating your own classes.
But if you want it simpler, there are other libraries, for my preference, The easiest one to use is JSON Path: https://github.com/json-path/JsonPath
I am currently working on a kind of weather app. Therefor I have to parse A JSON Object. I use GSON for that.
I always get an error.
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was
BEGIN_ARRAY at line 1 column 224 path $.list[0].weather
The JSON Object looks something like this:
{"city":{"id":1851632,"name":"Shuzenji"},
"coord":{"lon":138.933334,"lat":34.966671},
"country":"JP",
"cod":"200",
"message":0.0045,
"cnt":38,
"list":[{
"dt":1406106000,
"main":{
"temp":298.77,
"temp_min":298.77,
"temp_max":298.774,
"pressure":1005.93,
"sea_level":1018.18,
"grnd_level":1005.93,
"humidity":87,
"temp_kf":0.26},
"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],
"clouds":{"all":88},
"wind":{"speed":5.71,"deg":229.501},
"sys":{"pod":"d"},
"dt_txt":"2014-07-23 09:00:00"},
{
"dt":1406106000,
"main":{
"temp":298.77,
"temp_min":298.77,
"temp_max":298.774,
"pressure":1005.93,
"sea_level":1018.18,
"grnd_level":1005.93,
"humidity":87,
"temp_kf":0.26},
"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],
"clouds":{"all":88},
"wind":{"speed":5.71,"deg":229.501},
"sys":{"pod":"d"},
"dt_txt":"2014-07-23 09:00:00"}
]}
I created all the classes needed the "all in one" object is here:
public class AIOobject {
City city;
Coord coord;
String country;
String cod;
String message;
String cnt;
List[] list;
public AIOobject(City city, Coord coord, String country, String cod, String message, String cnt, List[] list) {
this.city = city;
this.coord = coord;
this.country = country;
this.cod = cod;
this.message = message;
this.cnt = cnt;
this.list = list;
}
}
The other classes are just saving data like:
public class Weather {
String id;
String main;
String description;
String icon;
public Weather(String id, String main, String description, String icon) {
this.id = id;
this.main = main;
this.description = description;
this.icon = icon;
}
}
My question is now why I get this error and how I get solve the problem.
Thanks for all responses
EDIT Fixed the JSON Object
~Paul
after fixing your JSON, you can try using an auto generator to create your gson file.
below is the auto-created file from http://www.jsonschema2pojo.org
-----------------------------------com.example.AIObject.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AIObject {
#SerializedName("city")
#Expose
private City city;
#SerializedName("coord")
#Expose
private Coord coord;
#SerializedName("country")
#Expose
private String country;
#SerializedName("cod")
#Expose
private String cod;
#SerializedName("message")
#Expose
private Double message;
#SerializedName("cnt")
#Expose
private Integer cnt;
#SerializedName("list")
#Expose
private java.util.List<com.example.List> list = null;
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public Coord getCoord() {
return coord;
}
public void setCoord(Coord coord) {
this.coord = coord;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCod() {
return cod;
}
public void setCod(String cod) {
this.cod = cod;
}
public Double getMessage() {
return message;
}
public void setMessage(Double message) {
this.message = message;
}
public Integer getCnt() {
return cnt;
}
public void setCnt(Integer cnt) {
this.cnt = cnt;
}
public java.util.List<com.example.List> getList() {
return list;
}
public void setList(java.util.List<com.example.List> list) {
this.list = list;
}
}
-----------------------------------com.example.City.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class City {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
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;
}
}
-----------------------------------com.example.Clouds.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Clouds {
#SerializedName("all")
#Expose
private Integer all;
public Integer getAll() {
return all;
}
public void setAll(Integer all) {
this.all = all;
}
}
-----------------------------------com.example.Coord.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
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;
}
}
-----------------------------------com.example.List.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class List {
#SerializedName("dt")
#Expose
private Integer dt;
#SerializedName("main")
#Expose
private Main main;
#SerializedName("weather")
#Expose
private java.util.List<Weather> weather = null;
#SerializedName("clouds")
#Expose
private Clouds clouds;
#SerializedName("wind")
#Expose
private Wind wind;
#SerializedName("sys")
#Expose
private Sys sys;
#SerializedName("dt_txt")
#Expose
private String dtTxt;
public Integer getDt() {
return dt;
}
public void setDt(Integer dt) {
this.dt = dt;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public java.util.List<Weather> getWeather() {
return weather;
}
public void setWeather(java.util.List<Weather> weather) {
this.weather = weather;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public String getDtTxt() {
return dtTxt;
}
public void setDtTxt(String dtTxt) {
this.dtTxt = dtTxt;
}
}
-----------------------------------com.example.Main.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Main {
#SerializedName("temp")
#Expose
private Double temp;
#SerializedName("temp_min")
#Expose
private Double tempMin;
#SerializedName("temp_max")
#Expose
private Double tempMax;
#SerializedName("pressure")
#Expose
private Double pressure;
#SerializedName("sea_level")
#Expose
private Double seaLevel;
#SerializedName("grnd_level")
#Expose
private Double grndLevel;
#SerializedName("humidity")
#Expose
private Integer humidity;
#SerializedName("temp_kf")
#Expose
private Double tempKf;
public Double getTemp() {
return temp;
}
public void setTemp(Double temp) {
this.temp = temp;
}
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 Double getPressure() {
return pressure;
}
public void setPressure(Double pressure) {
this.pressure = pressure;
}
public Double getSeaLevel() {
return seaLevel;
}
public void setSeaLevel(Double seaLevel) {
this.seaLevel = seaLevel;
}
public Double getGrndLevel() {
return grndLevel;
}
public void setGrndLevel(Double grndLevel) {
this.grndLevel = grndLevel;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public Double getTempKf() {
return tempKf;
}
public void setTempKf(Double tempKf) {
this.tempKf = tempKf;
}
}
-----------------------------------com.example.Sys.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Sys {
#SerializedName("pod")
#Expose
private String pod;
public String getPod() {
return pod;
}
public void setPod(String pod) {
this.pod = pod;
}
}
-----------------------------------com.example.Weather.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Weather {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("main")
#Expose
private String main;
#SerializedName("description")
#Expose
private String description;
#SerializedName("icon")
#Expose
private String icon;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
-----------------------------------com.example.Wind.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Wind {
#SerializedName("speed")
#Expose
private Double speed;
#SerializedName("deg")
#Expose
private Double deg;
public Double getSpeed() {
return speed;
}
public void setSpeed(Double speed) {
this.speed = speed;
}
public Double getDeg() {
return deg;
}
public void setDeg(Double deg) {
this.deg = deg;
}
}
City is missing the end curly brace at the end of the first line in the JSON. It should be:
"city":{"id":1851632,"name":"Shuzenji"}
You are trying to parse the "list" JSONArray as an array. GSON can only convert JSONArrays into a List and that's why changing list form List[] to ArrayList<List> would fix the issue.
So I am trying to make a weather app, the API works but only in certain areas. For now I am just trying to make a Toast of the API to make sure it works before I go on to do the rest of the app.
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.openweathermap.org/data/2.5/")
.addConverterFactory(GsonConverterFactory.create())
.build();
OpenWeatherMapClient api = retrofit.create(OpenWeatherMapClient.class);
Call<DailyWeather> call = api.getDailyWeather();
call.enqueue(new Callback<DailyWeather>()
{
#Override
public void onResponse(Call<DailyWeather> call, Response<DailyWeather> response)
{
Toast.makeText(MainActivity.this, (response.body().getWeather().getDescription()).toString(), Toast.LENGTH_SHORT).show();
for( Weather w : response.body().getWeather())
{
Log.d("Weather", w.getId().toString());
Log.d("Weather", w.getMain().toString());
Log.d("Weather", w.getDescription().toString());
}
}
So this is my MainActivity.java, if I replace getWeather().getDescription()) with .getCoord().getLat()) it works. The only thing I have noticed is the API section for weather is in sqaure brackets.
So if I run my API searching for 'Birmingham,uk' this is the json (after going through an online parser for easy reading'
{
"coord":{
"lon":-1.9,
"lat":52.48
},
"weather":[
{
"id":802,
"main":"Clouds",
"description":"scattered clouds",
"icon":"03d"
}
],
"base":"stations",
"main":{
"temp":282.57,
"pressure":1008,
"humidity":76,
"temp_min":282.15,
"temp_max":283.15
},
For reference I'll leave the Coord and Weather classes I have in case
the error is in there.
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
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;
}
}
And
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Weather {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("main")
#Expose
private String main;
#SerializedName("description")
#Expose
private String description;
#SerializedName("icon")
#Expose
private String icon;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
And the DailyWeather class as requested
public class DailyWeather {
#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;
}
}
The weather variable is a list, so to access it you should do:
List<Weather> weatherList = response.body().getWeather();
if(weatherList!=null && !weatherList.isEmpty()){
Toast.makeText(MainActivity.this, (weatherList.get(0).getDescription()).toString(), Toast.LENGTH_SHORT).show();
}
You weren't able to do getWeather().getDescription() because getWeather() returns a list. So you'd need to select an element in the list to only then do getDescription().
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 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.