I'm making Java Application which runs with C++ Server and want to receive a JSON Object from the server. Basiclly I'm sending LatLng(Latitude, Longtitude) to the server and it's returning me elements from the Google Maps API, but the problem is that the return elements have escape characters in them and I can't parse them with JSONObject.
#Override
protected void onPostExecute(string output) {
super.onPostExecute(output);
try {
JSONObject data = new JSONObject(output);
String test = data.getJSONObject("main_Points").getString("name");
System.out.print(test);
} catch(Exception ex) {
ex.printStackTrace();
}
}
And here's my JSON Object (Error:org.json.JSONException: Unterminated object at character 579)
{
"main_Points":{
"final":{
"lat":42.502812,
"lng":27.4691601,
"name":"бул. „Сан Стефано“ 62, 8001 ж.к. Братя Миладинови, Бургас, България"
},
"start":{
"lat":42.4912504,
"lng":27.4725683,
"name":"бул. „Иван Вазов“ 1, 8000 Бургас Център, Бургас, България"
}
},
"nearestPoints":{
"final":{
"lat":42.503294,
"lng":27.468482,
"name":"БСУ"
},
"start":{
"lat":42.490604,
"lng":27.474128,
"name":"Автогара Юг"
}
},
"polylines":{
"final":"qilbGgatfDR`Bo#?eA\\",
"middle":"}|ibGi`ufD#~#Ah#MVGMwB`##bCG~CeFtBiBr#yApAeBl#sBr#aDbAiC|#cCr#uJfCaDz#{ElAoCl#OC_B^}Bh#Gm#m#cF_A#eA\\",
"start":"iajbGqvtfDAaDvBa#FLLW#i#A_A"
}
}
You can create object from json string with :
http://www.jsonschema2pojo.org/
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("main_Points")
#Expose
private MainPoints mainPoints;
#SerializedName("nearestPoints")
#Expose
private NearestPoints nearestPoints;
#SerializedName("polylines")
#Expose
private Polylines polylines;
public MainPoints getMainPoints() {
return mainPoints;
}
public void setMainPoints(MainPoints mainPoints) {
this.mainPoints = mainPoints;
}
public NearestPoints getNearestPoints() {
return nearestPoints;
}
public void setNearestPoints(NearestPoints nearestPoints) {
this.nearestPoints = nearestPoints;
}
public Polylines getPolylines() {
return polylines;
}
public void setPolylines(Polylines polylines) {
this.polylines = polylines;
}
}
-----------------------------------com.example.Final.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Final {
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lng")
#Expose
private Double lng;
#SerializedName("name")
#Expose
private String name;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLng() {
return lng;
}
public void setLng(Double lng) {
this.lng = lng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
-----------------------------------com.example.Final_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Final_ {
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lng")
#Expose
private Double lng;
#SerializedName("name")
#Expose
private String name;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLng() {
return lng;
}
public void setLng(Double lng) {
this.lng = lng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
-----------------------------------com.example.MainPoints.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class MainPoints {
#SerializedName("final")
#Expose
private Final _final;
#SerializedName("start")
#Expose
private Start start;
public Final getFinal() {
return _final;
}
public void setFinal(Final _final) {
this._final = _final;
}
public Start getStart() {
return start;
}
public void setStart(Start start) {
this.start = start;
}
}
-----------------------------------com.example.NearestPoints.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class NearestPoints {
#SerializedName("final")
#Expose
private Final_ _final;
#SerializedName("start")
#Expose
private Start_ start;
public Final_ getFinal() {
return _final;
}
public void setFinal(Final_ _final) {
this._final = _final;
}
public Start_ getStart() {
return start;
}
public void setStart(Start_ start) {
this.start = start;
}
}
-----------------------------------com.example.Polylines.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Polylines {
#SerializedName("final")
#Expose
private String _final;
#SerializedName("middle")
#Expose
private String middle;
#SerializedName("start")
#Expose
private String start;
public String getFinal() {
return _final;
}
public void setFinal(String _final) {
this._final = _final;
}
public String getMiddle() {
return middle;
}
public void setMiddle(String middle) {
this.middle = middle;
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
}
-----------------------------------com.example.Start.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Start {
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lng")
#Expose
private Double lng;
#SerializedName("name")
#Expose
private String name;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLng() {
return lng;
}
public void setLng(Double lng) {
this.lng = lng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
-----------------------------------com.example.Start_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Start_ {
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lng")
#Expose
private Double lng;
#SerializedName("name")
#Expose
private String name;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLng() {
return lng;
}
public void setLng(Double lng) {
this.lng = lng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And
#Override
protected void onPostExecute(string output) {
super.onPostExecute(output);
try {
JSONObject data = new JSONObject(output);
Gson g = new Gson();
Example example = g.fromJson(data.toString(), Example.class);
} catch(Exception ex) {
ex.printStackTrace();
}
}
You will get everything in Example object.
I hope it will help your problem!
Related
I have this JSON response.
I want to fetch the times data that is inside datetime.
{
"code":200,
"status":"OK",
"results":{
"datetime":[
{
"times":{
"Imsak":"04:21",
"Sunrise":"-",
"Fajr":"04:31",
"Dhuhr":"11:41",
"Asr":"14:58",
"Sunset":"-",
"Maghrib":"17:54",
"Isha":"18:46",
"Midnight":"-"
},
"date":{
"timestamp":1617667200,
"gregorian":"2021-04-06",
"hijri":"1442-08-24"
}
}
],
"location":{
"latitude":-6.966667,
"longitude":110.416664,
"elevation":-9999.0,
"country":"",
"country_code":"ID",
"timezone":"Asia/Jakarta",
"local_offset":7.0
},
"settings":{
"timeformat":"HH:mm",
"school":"Ithna Ashari",
"juristic":"Shafii",
"highlat":"None",
"fajr_angle":18.0,
"isha_angle":17.0
}
}
}
How to get object "times" and take it into the map.
How to take the individual values as well as an array.
Below code will make "times" object. Like:
String json = "{\"code\":200,\"status\":\"OK\",\"results\":{\"datetime\":[{\"times\":{\"Imsak\":\"04:21\",\"Sunrise\":\"-\",\"Fajr\":\"04:31\",\"Dhuhr\":\"11:41\",\"Asr\":\"14:58\",\"Sunset\":\"-\",\"Maghrib\":\"17:54\",\"Isha\":\"18:46\",\"Midnight\":\"-\"},\"date\":{\"timestamp\":1617667200,\"gregorian\":\"2021-04-06\",\"hijri\":\"1442-08-24\"}}],\"location\":{\"latitude\":-6.966667,\"longitude\":110.416664,\"elevation\":-9999.0,\"country\":\"\",\"country_code\":\"ID\",\"timezone\":\"Asia/Jakarta\",\"local_offset\":7.0},\"settings\":{\"timeformat\":\"HH:mm\",\"school\":\"Ithna Ashari\",\"juristic\":\"Shafii\",\"highlat\":\"None\",\"fajr_angle\":18.0,\"isha_angle\":17.0}}}";
try {
JSONObject rootJsonObject = new JSONObject(json);
JSONObject resultJsonObject = rootJsonObject.getJSONObject("results");
JSONArray dateTimeJsonArray = resultJsonObject.getJSONArray("datetime");
JSONObject timeJsonObject = new JSONObject(dateTimeJsonArray.get(0).toString());
JSONObject timeJson = new JSONObject(timeJsonObject.getString("times"));
Log.d("TAG","Time json = "+timeJson);
}catch (JSONException jsonException){
Log.d("TAG","JSON Exception: "+jsonException.getLocalizedMessage());
}
public class Example {
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("status")
#Expose
private String status;
#SerializedName("results")
#Expose
private Results results;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Results getResults() {
return results;
}
public void setResults(Results results) {
this.results = results;
}
}
public class Results {
#SerializedName("datetime")
#Expose
private List<Datetime> datetime = null;
#SerializedName("location")
#Expose
private Location location;
#SerializedName("settings")
#Expose
private Settings settings;
public List<Datetime> getDatetime() {
return datetime;
}
public void setDatetime(List<Datetime> datetime) {
this.datetime = datetime;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Settings getSettings() {
return settings;
}
public void setSettings(Settings settings) {
this.settings = settings;
}
}
public class Datetime {
#SerializedName("times")
#Expose
private HashMap<String,String> times;
#SerializedName("date")
#Expose
private Date date;
public HashMap<String,String> getTimes() {
return times;
}
public void setTimes(HashMap<String,String> times) {
this.times = times;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
public class Settings {
#SerializedName("timeformat")
#Expose
private String timeformat;
#SerializedName("school")
#Expose
private String school;
#SerializedName("juristic")
#Expose
private String juristic;
#SerializedName("highlat")
#Expose
private String highlat;
#SerializedName("fajr_angle")
#Expose
private Double fajrAngle;
#SerializedName("isha_angle")
#Expose
private Double ishaAngle;
public String getTimeformat() {
return timeformat;
}
public void setTimeformat(String timeformat) {
this.timeformat = timeformat;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getJuristic() {
return juristic;
}
public void setJuristic(String juristic) {
this.juristic = juristic;
}
public String getHighlat() {
return highlat;
}
public void setHighlat(String highlat) {
this.highlat = highlat;
}
public Double getFajrAngle() {
return fajrAngle;
}
public void setFajrAngle(Double fajrAngle) {
this.fajrAngle = fajrAngle;
}
public Double getIshaAngle() {
return ishaAngle;
}
public void setIshaAngle(Double ishaAngle) {
this.ishaAngle = ishaAngle;
}
}
public class Location {
#SerializedName("latitude")
#Expose
private Double latitude;
#SerializedName("longitude")
#Expose
private Double longitude;
#SerializedName("elevation")
#Expose
private Double elevation;
#SerializedName("country")
#Expose
private String country;
#SerializedName("country_code")
#Expose
private String countryCode;
#SerializedName("timezone")
#Expose
private String timezone;
#SerializedName("local_offset")
#Expose
private Double localOffset;
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getElevation() {
return elevation;
}
public void setElevation(Double elevation) {
this.elevation = elevation;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public Double getLocalOffset() {
return localOffset;
}
public void setLocalOffset(Double localOffset) {
this.localOffset = localOffset;
}
}
This is my dto class and I try to map the field of entity becuse I want to use that in the service layer.
Blockquote
package com.prolifics.dto;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonInclude(Include.NON_NULL)
public class FacilityDTO {
private Integer id;
private String city;
private String name;
private String pin;
private String state;
private String status;
private float lattitude;
private float longitude;
private Map<String,Integer> vaccineStock;
public Map<String, Integer> getVaccineStock() {
return vaccineStock;
}
public void setVaccineStock(Map<String, Integer> vaccineStock) {
this.vaccineStock = vaccineStock;
}
public float getLattitude() {
return lattitude;
}
public void setLattitude(float lattitude) {
this.lattitude = lattitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
In my facilityVaccineEntity there is a stock variable of int type and I want to map that field in my dto class as it does not contain stock field so that I can access it from service class. how to do this?
#Repository
public interface FacilityVaccineRepository extends CrudRepository<FacilityVaccine,Integer>{
public FacilityVaccine stock(int stock);
}
So i have this data as below and i am trying to parse the data, i can see a lot about parsing JSONArrays online however, not so much on objects within objects. I have had a go and am getting an error. Here is the Json response I am only trying to return the marked fields:
{
"geomagnetic-field-model-result": {
"model": "wmm",
"model_revision": "2020",
"date": {
"value": "2020-07-14"
},
"coordinates": {
"latitude": {
"units": "deg (north)",
"value": 0.0
},
"longitude": {
"units": "deg (east)",
"value": 0.0
},
"altitude": {
"units": "km",
"value": 0.00
}
},
"field-value": {
"total-intensity": {
"units": "nT",
"value": 123 //Return this*****************
},
"declination": {
"units": "deg (east)",
"value": -123 //Return this*****************
},
"inclination": {
"units": "deg (down)",
"value": 123 //Return this*****************
},
"north-intensity": {
"units": "nT",
"value": 123
},
"east-intensity": {
"units": "nT",
"value": -123
},
"vertical-intensity": {
"units": "nT",
"value": 123
},
"horizontal-intensity": {
"units": "nT",
"value": 123
}
},
"secular-variation": {
"total-intensity": {
"units": "nT/y",
"value": 123
},
"declination": {
"units": "arcmin/y (east)",
"value": 123
},
"inclination": {
"units": "arcmin/y (down)",
"value": 123
},
"north-intensity": {
"units": "nT/y",
"value": 123
},
"east-intensity": {
"units": "nT/y",
"value": 123
},
"vertical-intensity": {
"units": "nT/y",
"value": 123
},
"horizontal-intensity": {
"units": "nT/y",
"value": 123
}
}
}
}
My attempt at parsing currently looks like this:
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response;
String totalIntensity = jsonObject.getJSONObject("field-value").getJSONObject("total-intensity").getString("value");
String declination = jsonObject.getJSONObject("field-value").getJSONObject("declination").getString("value");
String inclination = jsonObject.getJSONObject("field-value").getJSONObject("inclination").getString("value");
} catch (JSONException e) {
Log.d("geoData", "Error recorded");
e.printStackTrace();
}
}
Am i totally wrong? Hopefully this is very easy for someone to put me right.
I assume that the response you get in the method is the whole JSON object that you have posted here.
You have a few issues:
Your data is not String it is Double or Integer, so you should use getDouble for example.
You forgot about one additional node geomagnetic-field-model-result.
You don't need to assign internal JSONObject jsonObject you can just use response.
To get to the values you should:
public void onResponse(JSONObject response) {
try {
// JSONObject jsonObject = response; you don't need this
Double totalIntensity = response
.getJSONObject("geomagnetic-field-model-result")
.getJSONObject("field-value")
.getJSONObject("total-intensity")
.getDouble("value");
Double declination = response
.getJSONObject("geomagnetic-field-model-result")
.getJSONObject("field-value")
.getJSONObject("declination")
.getDouble("value");
Double inclination = response
.getJSONObject("geomagnetic-field-model-result")
.getJSONObject("field-value")
.getJSONObject("inclination")
.getDouble("value");
// use it somehow
} catch (JSONException e) {
Log.d("geoData", "Error recorded");
e.printStackTrace();
}
}
Create a Schema and use the return values, it's much easier to work with
Example schema for your returned response made from http://www.jsonschema2pojo.org/
-----------------------------------com.example.Altitude.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Altitude {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Double value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
}
-----------------------------------com.example.Coordinates.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Coordinates {
#SerializedName("latitude")
#Expose
private Latitude latitude;
#SerializedName("longitude")
#Expose
private Longitude longitude;
#SerializedName("altitude")
#Expose
private Altitude altitude;
public Latitude getLatitude() {
return latitude;
}
public void setLatitude(Latitude latitude) {
this.latitude = latitude;
}
public Longitude getLongitude() {
return longitude;
}
public void setLongitude(Longitude longitude) {
this.longitude = longitude;
}
public Altitude getAltitude() {
return altitude;
}
public void setAltitude(Altitude altitude) {
this.altitude = altitude;
}
}
-----------------------------------com.example.Date.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Date {
#SerializedName("value")
#Expose
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
-----------------------------------com.example.Declination.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Declination {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.Declination_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Declination_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.EastIntensity.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class EastIntensity {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.EastIntensity_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class EastIntensity_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("geomagnetic-field-model-result")
#Expose
private GeomagneticFieldModelResult geomagneticFieldModelResult;
public GeomagneticFieldModelResult getGeomagneticFieldModelResult() {
return geomagneticFieldModelResult;
}
public void setGeomagneticFieldModelResult(GeomagneticFieldModelResult geomagneticFieldModelResult) {
this.geomagneticFieldModelResult = geomagneticFieldModelResult;
}
}
-----------------------------------com.example.FieldValue.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FieldValue {
#SerializedName("total-intensity")
#Expose
private TotalIntensity totalIntensity;
#SerializedName("declination")
#Expose
private Declination declination;
#SerializedName("inclination")
#Expose
private Inclination inclination;
#SerializedName("north-intensity")
#Expose
private NorthIntensity northIntensity;
#SerializedName("east-intensity")
#Expose
private EastIntensity eastIntensity;
#SerializedName("vertical-intensity")
#Expose
private VerticalIntensity verticalIntensity;
#SerializedName("horizontal-intensity")
#Expose
private HorizontalIntensity horizontalIntensity;
public TotalIntensity getTotalIntensity() {
return totalIntensity;
}
public void setTotalIntensity(TotalIntensity totalIntensity) {
this.totalIntensity = totalIntensity;
}
public Declination getDeclination() {
return declination;
}
public void setDeclination(Declination declination) {
this.declination = declination;
}
public Inclination getInclination() {
return inclination;
}
public void setInclination(Inclination inclination) {
this.inclination = inclination;
}
public NorthIntensity getNorthIntensity() {
return northIntensity;
}
public void setNorthIntensity(NorthIntensity northIntensity) {
this.northIntensity = northIntensity;
}
public EastIntensity getEastIntensity() {
return eastIntensity;
}
public void setEastIntensity(EastIntensity eastIntensity) {
this.eastIntensity = eastIntensity;
}
public VerticalIntensity getVerticalIntensity() {
return verticalIntensity;
}
public void setVerticalIntensity(VerticalIntensity verticalIntensity) {
this.verticalIntensity = verticalIntensity;
}
public HorizontalIntensity getHorizontalIntensity() {
return horizontalIntensity;
}
public void setHorizontalIntensity(HorizontalIntensity horizontalIntensity) {
this.horizontalIntensity = horizontalIntensity;
}
}
-----------------------------------com.example.GeomagneticFieldModelResult.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class GeomagneticFieldModelResult {
#SerializedName("model")
#Expose
private String model;
#SerializedName("model_revision")
#Expose
private String modelRevision;
#SerializedName("date")
#Expose
private Date date;
#SerializedName("coordinates")
#Expose
private Coordinates coordinates;
#SerializedName("field-value")
#Expose
private FieldValue fieldValue;
#SerializedName("secular-variation")
#Expose
private SecularVariation secularVariation;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getModelRevision() {
return modelRevision;
}
public void setModelRevision(String modelRevision) {
this.modelRevision = modelRevision;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public FieldValue getFieldValue() {
return fieldValue;
}
public void setFieldValue(FieldValue fieldValue) {
this.fieldValue = fieldValue;
}
public SecularVariation getSecularVariation() {
return secularVariation;
}
public void setSecularVariation(SecularVariation secularVariation) {
this.secularVariation = secularVariation;
}
}
-----------------------------------com.example.HorizontalIntensity.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class HorizontalIntensity {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.HorizontalIntensity_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class HorizontalIntensity_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.Inclination.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Inclination {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.Inclination_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Inclination_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.Latitude.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Latitude {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Double value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
}
-----------------------------------com.example.Longitude.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Longitude {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Double value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
}
-----------------------------------com.example.NorthIntensity.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class NorthIntensity {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.NorthIntensity_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class NorthIntensity_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.SecularVariation.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class SecularVariation {
#SerializedName("total-intensity")
#Expose
private TotalIntensity_ totalIntensity;
#SerializedName("declination")
#Expose
private Declination_ declination;
#SerializedName("inclination")
#Expose
private Inclination_ inclination;
#SerializedName("north-intensity")
#Expose
private NorthIntensity_ northIntensity;
#SerializedName("east-intensity")
#Expose
private EastIntensity_ eastIntensity;
#SerializedName("vertical-intensity")
#Expose
private VerticalIntensity_ verticalIntensity;
#SerializedName("horizontal-intensity")
#Expose
private HorizontalIntensity_ horizontalIntensity;
public TotalIntensity_ getTotalIntensity() {
return totalIntensity;
}
public void setTotalIntensity(TotalIntensity_ totalIntensity) {
this.totalIntensity = totalIntensity;
}
public Declination_ getDeclination() {
return declination;
}
public void setDeclination(Declination_ declination) {
this.declination = declination;
}
public Inclination_ getInclination() {
return inclination;
}
public void setInclination(Inclination_ inclination) {
this.inclination = inclination;
}
public NorthIntensity_ getNorthIntensity() {
return northIntensity;
}
public void setNorthIntensity(NorthIntensity_ northIntensity) {
this.northIntensity = northIntensity;
}
public EastIntensity_ getEastIntensity() {
return eastIntensity;
}
public void setEastIntensity(EastIntensity_ eastIntensity) {
this.eastIntensity = eastIntensity;
}
public VerticalIntensity_ getVerticalIntensity() {
return verticalIntensity;
}
public void setVerticalIntensity(VerticalIntensity_ verticalIntensity) {
this.verticalIntensity = verticalIntensity;
}
public HorizontalIntensity_ getHorizontalIntensity() {
return horizontalIntensity;
}
public void setHorizontalIntensity(HorizontalIntensity_ horizontalIntensity) {
this.horizontalIntensity = horizontalIntensity;
}
}
-----------------------------------com.example.TotalIntensity.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class TotalIntensity {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.TotalIntensity_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class TotalIntensity_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.VerticalIntensity.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class VerticalIntensity {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
-----------------------------------com.example.VerticalIntensity_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class VerticalIntensity_ {
#SerializedName("units")
#Expose
private String units;
#SerializedName("value")
#Expose
private Integer value;
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
So now along as the schema doesn't change this will return the values in the correct format
You can use Jackson like this:
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(input);
System.out.println(jsonNode.get("geomagnetic-field-model-result").get("field-value").get("total-intensity").get("value"));
Here's an example of my JSON:
{
"status": "ok",
"rowCount": 60,
"pageCount": 6,
"value": [{
"CustomerID": 1911,
"CustomerTypeID": 3,
...
}
]
}
My POJO:
#SerializedName("CustomerID")
public Integer CustomerID;
#SerializedName("CustomerTypeID")
public Integer CustomerTypeID;
I want to pull everything under value.
How do I do this using Google's GSON?
I've tried doing it as I would normally, but for, obvious reasons, it didn't work:
Type collectionType = new TypeToken<ArrayList<Customer>>() {}.getType();
return gson.fromJson(json, collectionType);
You can not skip root JSON object. The simplest solution in this case is - create root POJO:
class Response {
#SerializedName("value")
private List<Customer> customers;
// getters, setters
}
And you can use it as below:
return gson.fromJson(json, Response.class).getCustomers();
You don't need to worry writing your own POJO.
just visit http://www.jsonschema2pojo.org/
and paste here your JSON data, it'll automatically return you converted classes as below
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("status")
#Expose
private String status;
#SerializedName("rowCount")
#Expose
private Integer rowCount;
#SerializedName("pageCount")
#Expose
private Integer pageCount;
#SerializedName("value")
#Expose
private List<Value> value = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getRowCount() {
return rowCount;
}
public void setRowCount(Integer rowCount) {
this.rowCount = rowCount;
}
public Integer getPageCount() {
return pageCount;
}
public void setPageCount(Integer pageCount) {
this.pageCount = pageCount;
}
public List<Value> getValue() {
return value;
}
public void setValue(List<Value> value) {
this.value = value;
}
}
-----------------------------------com.example.Value.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Value {
#SerializedName("CustomerID")
#Expose
private Integer customerID;
#SerializedName("CustomerTypeID")
#Expose
private Integer customerTypeID;
public Integer getCustomerID() {
return customerID;
}
public void setCustomerID(Integer customerID) {
this.customerID = customerID;
}
public Integer getCustomerTypeID() {
return customerTypeID;
}
public void setCustomerTypeID(Integer customerTypeID) {
this.customerTypeID = customerTypeID;
}
}
The above two classes are auto generated by website.
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ExampleClass {
#SerializedName("status")
#Expose
private String status;
#SerializedName("rowCount")
#Expose
private int rowCount;
#SerializedName("pageCount")
#Expose
private int pageCount;
#SerializedName("value")
#Expose
private List<Value> value = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getRowCount() {
return rowCount;
}
public void setRowCount(int rowCount) {
this.rowCount = rowCount;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public List<Value> getValue() {
return value;
}
public void setValue(List<Value> value) {
this.value = value;
}
}
-----------------------------------Value.java-----------------------------------
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Value {
#SerializedName("CustomerID")
#Expose
private int customerID;
#SerializedName("CustomerTypeID")
#Expose
private int customerTypeID;
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public int getCustomerTypeID() {
return customerTypeID;
}
public void setCustomerTypeID(int customerTypeID) {
this.customerTypeID = customerTypeID;
}
}
/********* parsing with Gson ******/
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
ExampleClass resultObj = gson.fromJson(jsonObject.toString(), ExampleClass.class);
List<Value> yourListOfCustomerValues = resultObj.getValue();
You can refer to this amazing post on mapping of arrays and lists of objects with Gson by Norman Peitek
Basics of Gson, model annotations and mapping of nested objects
I have a json string something similar
{"results":
[{"_type":"Position","_id":377078,"name":"Potsdam, Germany","type":"location","geo_position":{"latitude":52.39886,"longitude":13.06566}},
{"_type":"Position","_id":410978,"name":"Potsdam, USA","type":"location","geo_position":{"latitude":44.66978,"longitude":-74.98131}}]}
I am trying to convert to
{"results":
[{"_type":"Position","_id":377078,"name":"Potsdam, Germany","type":"location","latitude":52.39886,"longitude":13.06566},
{"_type":"Position","_id":410978,"name":"Potsdam, USA","type":"location","latitude":44.66978,"longitude":-74.98131}]}
I am converting to java and again converting back using But I am gettin null in data
SourceJSON data=new Gson().fromJson(jsonArray, SourceJSON.class);
DestinationJSON destdata = new DestinationJSON();
destdata.setLatitide(data.getGeoLocation().getLatitide());
destdata.setLongitude(data.getGeoLocation().getLongitude());
destdata.setId(data.getId());
destdata.setType(data.getType());
destdata.setName(data.getName());
destdata.set_type(data.get_type());
Gson gson = new Gson();
String json = gson.toJson(destdata);
below are my beans
public class SourceJSON implements Serializable {
private List<GEOLocation> geoLocations;
private String _type;
private String id;
private String name;
private String type;
public String get_type() {
return _type;
}
public List<GEOLocation> getGeoLocations() {
return geoLocations;
}
public void setGeoLocations(List<GEOLocation> geoLocations) {
this.geoLocations = geoLocations;
}
public void set_type(String _type) {
this._type = _type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
and
public class GEOLocation implements Serializable{
private String latitide;
private String longitude;
public String getLatitide() {
return latitide;
}
public void setLatitide(String latitide) {
this.latitide = latitide;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
and destination java
public class DestinationJSON implements Serializable {
private String _type;
private String id;
private String name;
private String type;
private String latitide;
private String longitude;
public String get_type() {
return _type;
}
public void set_type(String _type) {
this._type = _type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLatitide() {
return latitide;
}
public void setLatitide(String latitide) {
this.latitide = latitide;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
All you need is this. You can try this class in your IDE with a simple copy&paste.
package stackoverflow.questions;
import java.util.*;
import com.google.gson.Gson;
public class Q20433539{
public static void main(String[] args){
String json = "{\"results\":"+
"[{\"_type\":\"Position\",\"_id\":377078,\"name\":\"Potsdam, Germany\",\"type\":\"location\",\"geo_position\":{\"latitude\":52.39886,\"longitude\":13.06566}},"+
"{\"_type\":\"Position\",\"_id\":410978,\"name\":\"Potsdam, USA\",\"type\":\"location\",\"geo_position\":{\"latitude\":44.66978,\"longitude\":-74.98131}}]}";
Gson gson = new Gson();
Map m = gson.fromJson(json, Map.class);
List<Map> innerList = (List<Map>) m.get("results");
for(Map result: innerList){
Map<String, Double> geo_position = (Map<String, Double>) result.get("geo_position");
result.put("latitude", geo_position.get("latitude"));
result.put("longitude", geo_position.get("longitude"));
result.remove("geo_position");
}
System.out.println(gson.toJson(m));
}
}
Of course, it works under the assumption that you always want to flat geo information.
Explanation: It's convenient to use POJO when working with Gson, but it's not the only way. Gson can also deseralize to Arrays/Maps if you do not specify the expected result. So I did, and then I manipulated the structure to unfold your data. After that, Gson can serialize Arrays/Maps structure again to your desidered JSON.