ObjectMapper- Can not deserialize instance java.lang.Double - java

I want to get data from the string send by Node.js with that code:
User[] user2 = mapper.readValue(resultPayload, User[].class);
My User class:
public class User {
private double lat;
private double lon;
public User() {
}
public User(double lat, double lon) {
this.lat = lat;
this.lon = lon;
}
public double getLocationLat(){return lat;}
public void setLocationLat(double lat){this.lat = lat;}
public double getLocationLon(){return lon;}
public void setLocationLon(double lon){this.lon = lon;}
}
But I get such an warning:
WARNING: could not load Java7 Path class
/com.amazon.mysampleapp W/System.err: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.Double out of START_OBJECT token
My JSON string contains:
[{"locationLon":{"N":"16.946397721767426"},"locationLat":{"N":"52.447558225994904"}},{"locationLon":{"N":"16.88841037452221"},"locationLat":{"N":"52.44599882989592"}},{"locationLon":{"N":"16.94861490279436"},"locationLat":{"N":"52.44514319230585"}}]

Step 1: Location.java
import com.fasterxml.jackson.annotation.JsonProperty;
public class Location {
private double N;
public Location() {
}
public Location(double n) {
N = n;
}
#JsonProperty("N")
public double getN() {
return N;
}
public void setN(double n) {
N = n;
}
#Override
public String toString() {
return "N=" + N;
}
}
Step 2: User.java
public class User {
private Location locationLat;
private Location locationLon;
public User() {
}
public User(Location locationLat, Location locationLon) {
super();
this.locationLat = locationLat;
this.locationLon = locationLon;
}
public Location getLocationLat() {
return locationLat;
}
public void setLocationLat(Location locationLat) {
this.locationLat = locationLat;
}
public Location getLocationLon() {
return locationLon;
}
public void setLocationLon(Location locationLon) {
this.locationLon = locationLon;
}
#Override
public String toString() {
return "User [locationLat=" + locationLat + ", locationLon=" + locationLon + "]";
}
}
Step 3:
String resultPayload=new String(Files.readAllBytes(new File("D:/test3.json").toPath()));
ObjectMapper mapper = new ObjectMapper();
User[] users = mapper.readValue(resultPayload, User[].class);
System.out.println(Arrays.toString(users));
Please consider making all of the above changes and see the result.

Related

Spring boot getting error on restTemplate.getForObject json parsing

I want to parse this json string but i am getting error, i tried with different way but it is not working
My error
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of arrest_warrants out of START_ARRAY token
{
"arrest_warrants": [
{
"issuing_country_id": "CO",
"charge": "dfdfd",
"charge_translation": null
}
],
"weight": 0,
"forename": "MOISES",
"date_of_birth": "1965/06/02",
"entity_id": "2021/40054"
}
Parse calling: i am getting error on below line
Interpoldetails intterdt = restTemplate.getForObject("xxxurl"+id, Interpoldetails.class);
My class
#JsonIgnoreProperties(ignoreUnknown = true)
public class Interpoldetails {
private Integer weight;
private String date_of_birth;
private String entity_id;
private String name;
private arrest_warrants arrest_warrants;
private String[] languages_spoken_ids;
private Integer height;
private Integer sex_id;
private String country_of_birth_id;
private String place_of_birth;
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public String getDate_of_birth() {
return date_of_birth;
}
public void setDate_of_birth(String date_of_birth) {
this.date_of_birth = date_of_birth;
}
public String getEntity_id() {
return entity_id;
}
public void setEntity_id(String entity_id) {
this.entity_id = entity_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getLanguages_spoken_ids() {
return languages_spoken_ids;
}
public void setLanguages_spoken_ids(String[] languages_spoken_ids) {
this.languages_spoken_ids = languages_spoken_ids;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getSex_id() {
return sex_id;
}
public void setSex_id(Integer sex_id) {
this.sex_id = sex_id;
}
public String getCountry_of_birth_id() {
return country_of_birth_id;
}
public void setCountry_of_birth_id(String country_of_birth_id) {
this.country_of_birth_id = country_of_birth_id;
}
public String getPlace_of_birth() {
return place_of_birth;
}
public void setPlace_of_birth(String place_of_birth) {
this.place_of_birth = place_of_birth;
}
public arrest_warrants getArrest_warrants() {
return arrest_warrants;
}
public void setArrest_warrants(arrest_warrants arrest_warrants) {
this.arrest_warrants = arrest_warrants;
}
}
My inner class
#JsonIgnoreProperties(ignoreUnknown = true)
public class arrest_warrants {
private String issuing_country_id;
private String charge;
public String getIssuing_country_id() {
return issuing_country_id;
}
public void setIssuing_country_id(String issuing_country_id) {
this.issuing_country_id = issuing_country_id;
}
public String getCharge() {
return charge;
}
public void setCharge(String charge) {
this.charge = charge;
}
}
it should be arrest_warrants[] not String[]
As arrest_warrants is an array of objects you can create arrest_warrant object and in Interpoldetails class, use private List<arrest_warrant> arrest_warrants

Getting null from POJO after using JACKSON ObjectMapper

I'm struggling whit this problem for a while and can't find a solution.
My intention is to retrieve a POJO from the following JSON using Jackson:
{
"date": "2018-11-27",
"rates": {
"BGN": 1.9558,
"CAD": 1.5018,
"BRL": 4.4011,
"HUF": 324.06,
"DKK": 7.4617,
"JPY": 128.66,
"ILS": 4.2215,
"TRY": 5.9313,
"RON": 4.6583,
"GBP": 0.88748,
"PHP": 59.439,
"HRK": 7.4275,
"NOK": 9.7325,
"USD": 1.1328,
"MXN": 23.1784,
"AUD": 1.5631,
"IDR": 16410.59,
"KRW": 1279.17,
"HKD": 8.8679,
"ZAR": 15.632,
"ISK": 141,
"CZK": 25.914,
"THB": 37.371,
"MYR": 4.7498,
"NZD": 1.6647,
"PLN": 4.2902,
"SEK": 10.2823,
"RUB": 75.6401,
"CNY": 7.8708,
"SGD": 1.5582,
"CHF": 1.1309,
"INR": 80.162
},
"base": "EUR"
}
I solved it with the following code:
public class JsonToPojo {
private static final String URL_LATEST = "https://api.exchangeratesapi.io/latest";
public static String getJson() {
try {
URL url = new URL(URL_LATEST);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = bufferedReader.readLine()) != null) {
System.out.println(inputLine);
response.append(inputLine);
}
bufferedReader.close();
urlConnection.disconnect();
return response.toString();
} catch (IOException e) {
e.getStackTrace();
return null;
}
}
}
This is my POJO:
public class Currency {
private String date;
private Rates rates;
private String base;
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Rates getRates() {
return rates;
}
public void setRates(Rates rates) {
this.rates = rates;
}
}
Class using ObjectMapper:
public class CurrencyService {
public static Currency getLatestCurrency(){
try {
ObjectMapper mapper = new ObjectMapper();
Currency currency = mapper.readValue(JsonToPojo.getJson(), Currency.class);
return currency;
}catch (IOException e){
e.getStackTrace();
return null;
}
}
}
When I'm trying to call the get method on my POJO object, I'm getting a NullPointException, so something is wrong with databinding.
my Rates class.
public class Rates {
private float BGN;
private float CAD;
private float BRL;
private float HUF;
private float DKK;
private float JPY;
private float ILS;
private float TRY;
private float RON;
private float GBP;
private float PHP;
private float HRK;
private float NOK;
private float ZAR;
private float MXD;
private float AUD;
private float USD;
private float KRW;
private float HKD;
private float EUR;
private float ISK;
private float CZK;
private float THB;
private float MYR;
private float NZD;
private float PLN;
private float CHF;
private float SEK;
private float CNY;
private float SGD;
private float INR;
private float IDR;
private float RUB;
public void setBGN(Float BGN) {
this.BGN = BGN;
}
public void setCAD(Float CAD) {
this.CAD = CAD;
}
public void setBRL(Float BRL) {
this.BRL = BRL;
}
public void setHUF(Float HUF) {
this.HUF = HUF;
}
public void setDKK(Float DKK) {
this.DKK = DKK;
}
public void setJPY(Float JPY) {
this.JPY = JPY;
}
public void setILS(Float ILS) {
this.ILS = ILS;
}
public void setTRY(Float TRY) {
this.TRY = TRY;
}
public void setRON(Float RON) {
this.RON = RON;
}
public void setGBP(Float GBP) {
this.GBP = GBP;
}
public void setPHP(Float PHP) {
this.PHP = PHP;
}
public void setHRK(Float HRK) {
this.HRK = HRK;
}
public void setNOK(Float NOK) {
this.NOK = NOK;
}
public void setZAR(Float ZAR) {
this.ZAR = ZAR;
}
public void setMXD(Float MXD) {
this.MXD = MXD;
}
public void setAUD(Float AUD) {
this.AUD = AUD;
}
public void setUSD(Float USD) {
this.USD = USD;
}
public void setKRW(Float KRW) {
this.KRW = KRW;
}
public void setHKD(Float HKD) {
this.HKD = HKD;
}
public void setEUR(Float EUR) {
this.EUR = EUR;
}
public void setISK(Float ISK) {
this.ISK = ISK;
}
public void setCZK(Float CZK) {
this.CZK = CZK;
}
public void setTHB(Float THB) {
this.THB = THB;
}
public void setMYR(Float MYR) {
this.MYR = MYR;
}
public void setNZD(Float NZD) {
this.NZD = NZD;
}
public void setPLN(Float PLN) {
this.PLN = PLN;
}
public void setCHF(Float CHF) {
this.CHF = CHF;
}
public void setSEK(Float SEK) {
this.SEK = SEK;
}
public void setCNY(Float CNY) {
this.CNY = CNY;
}
public void setSGD(Float SGD) {
this.SGD = SGD;
}
public void setINR(Float INR) {
this.INR = INR;
}
public void setIDR(Float IDR) {
this.IDR = IDR;
}
public void setRUB(Float RUB) {
this.RUB = RUB;
}
public Float getBGN() {
return BGN;
}
public Float getCAD() {
return CAD;
}
public Float getBRL() {
return BRL;
}
public Float getHUF() {
return HUF;
}
public Float getDKK() {
return DKK;
}
public Float getJPY() {
return JPY;
}
public Float getILS() {
return ILS;
}
public Float getTRY() {
return TRY;
}
public Float getRON() {
return RON;
}
public Float getGBP() {
return GBP;
}
public Float getPHP() {
return PHP;
}
public Float getHRK() {
return HRK;
}
public Float getNOK() {
return NOK;
}
public Float getZAR() {
return ZAR;
}
public Float getMXD() {
return MXD;
}
public Float getAUD() {
return AUD;
}
public Float getUSD() {
return USD;
}
public Float getKRW() {
return KRW;
}
public Float getHKD() {
return HKD;
}
public Float getEUR() {
return EUR;
}
public Float getISK() {
return ISK;
}
public Float getCZK() {
return CZK;
}
public Float getTHB() {
return THB;
}
public Float getMYR() {
return MYR;
}
public Float getNZD() {
return NZD;
}
public Float getPLN() {
return PLN;
}
public Float getCHF() {
return CHF;
}
public Float getSEK() {
return SEK;
}
public Float getCNY() {
return CNY;
}
public Float getSGD() {
return SGD;
}
public Float getINR() {
return INR;
}
public Float getIDR() {
return IDR;
}
public Float getRUB() {
return RUB;
}
}
I've checked your code locally, and have got it working. I didn't have a Rates class, so I used a Map instead (to map the name, with the rate (float)):
import java.util.Map;
public class Currency {
private String date;
private Map<String, Float> rates;
private String base;
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Map<String, Float> getRates() {
return rates;
}
public Float getSingleRate(String rateKey) {
if (rates.containsKey(rateKey)) {
return rates.get(rateKey);
}
return 0.0F;
}
public void setRates(Map<String, Float> rates) {
this.rates = rates;
}
}
I have added the following main() method to your JSonToPojo class:
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
Currency currency = new Currency();
String jsonStr = getJson();
try {
currency = mapper.readValue(jsonStr, Currency.class);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(jsonStr);
System.out.println(currency.getSingleRate("BGN"));
System.out.println("finished");
}
Running the main() method, produces the following output (I have used [snip] instead of printing out all the JSon (twice)):
{"date":"2018-11-27","rates": {"BGN":1.9558, [snip] }
{"date":"2018-11-27","rates": {"BGN":1.9558, [snip] }
1.9558
finished
The output for "BGN" is:
1.9558
You can refer to http://www.jsonschema2pojo.org/ to get the correct pojo for your json.
Below is the one I created (moderatley modified)
You can replace like Object date with Date date and so on. If it doesn't work than there is probably some error in your POJO
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class Example {
#JsonProperty("date")
private Object date;
#JsonProperty("rates")
private Object rates;
#JsonProperty("base")
private Object base;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("date")
public Object getDate() {
return date;
}
#JsonProperty("date")
public void setDate(Object date) {
this.date = date;
}
#JsonProperty("rates")
public Object getRates() {
return rates;
}
#JsonProperty("rates")
public void setRates(Object rates) {
this.rates = rates;
}
#JsonProperty("base")
public Object getBase() {
return base;
}
#JsonProperty("base")
public void setBase(Object base) {
this.base = base;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
#Override
public String toString() {
return "date:" + date.toString() +
",\nrates:" + rates.toString() +
",\nbase: " + base.toString();
}
}
And here is the driver class in which you can read the object and pass in the user defined file path ( i have set it to "test-json.json"). You can update this with your local file path address.
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String... args){
Main main = new Main();
Example example = main.readObjectDataFromJsonFile(Example.class,"test-json.json");
System.out.println(example);
}
public <T> T readObjectDataFromJsonFile(Class<T> clazz, String jsonFilePath) {
T populatedObject = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
String objectJson = "";
Stream<String> lines = Files.lines(Paths.get(jsonFilePath));
objectJson = lines.collect(Collectors.joining());
lines.close();
populatedObject = objectMapper.readValue(objectJson, clazz);
} catch (IOException ioException) {
System.out.println("Exception in reading json file");
System.out.println(ioException.getMessage());
}
return populatedObject;
}
}
you can use
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
without any change to your Pojos, but I had to add MXN as a property to Rates class. But ideal way to handle this is having a Map for the rates. Because it can change any time as I understood, either way its easier for access. So change Currency class as follows.
public class Currency {
private String date;
private Map<String, Float> rates;
private String base;
// getters and setters
}
access exchange rates as getRates().get('MXN') // returns value.

Android: Draw direction in google map java

how to find the best route for multiple locations in google maps api in android? I have some locations as LatLng but I dont know how specify a optimal route
ArrayList<LatLng> directionPoint = latLongList;
PolylineOptions rectLine = new PolylineOptions().width(8).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
// Adding route on the map
map.addPolyline(rectLine);
Try this , pass your list of latlongs in latLongList
Using Google maps direction api you can acheive it, follow the documentation about using waypoints -
https://developers.google.com/maps/documentation/directions/intro#Waypoints
Now a fully functional api looks like this -
https://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&key=YOUR_API_KEY
Here origin = starting point, destination = Ending point, waypoints = points that you want to cover, optimize:true = the route through the given waypoints will be optimized(i.e following Traveling Salesman Problem) and key = your map api key.
Now in order to save the api response here is the model class -
public class DirectionApiResponse {
private ArrayList<Geocoded_waypoints> geocoded_waypoints;
private String status;
private ArrayList<Routes> routes;
public ArrayList<Geocoded_waypoints> getGeocoded_waypoints ()
{
return geocoded_waypoints;
}
public void setGeocoded_waypoints (ArrayList<Geocoded_waypoints> geocoded_waypoints)
{
this.geocoded_waypoints = geocoded_waypoints;
}
public String getStatus ()
{
return status;
}
public void setStatus (String status)
{
this.status = status;
}
public ArrayList<Routes> getRoutes ()
{
return routes;
}
public void setRoutes (ArrayList<Routes> routes)
{
this.routes = routes;
}
#Override
public String toString()
{
return "ClassPojo [geocoded_waypoints = "+geocoded_waypoints+", status = "+status+", routes = "+routes+"]";
}
public class Geocoded_waypoints
{
private String place_id;
private String geocoder_status;
private ArrayList<String> types;
public String getPlace_id ()
{
return place_id;
}
public void setPlace_id (String place_id)
{
this.place_id = place_id;
}
public String getGeocoder_status ()
{
return geocoder_status;
}
public void setGeocoder_status (String geocoder_status)
{
this.geocoder_status = geocoder_status;
}
public ArrayList<String> getTypes ()
{
return types;
}
public void setTypes (ArrayList<String> types)
{
this.types = types;
}
#Override
public String toString()
{
return "ClassPojo [place_id = "+place_id+", geocoder_status = "+geocoder_status+", types = "+types+"]";
}
}
public class Routes {
private String summary;
private Bounds bounds;
private String copyrights;
private ArrayList<String> waypoint_order;
private ArrayList<Legs> legs;
private ArrayList<String> warnings;
private Overview_polyline overview_polyline;
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public Bounds getBounds() {
return bounds;
}
public void setBounds(Bounds bounds) {
this.bounds = bounds;
}
public String getCopyrights() {
return copyrights;
}
public void setCopyrights(String copyrights) {
this.copyrights = copyrights;
}
public ArrayList<String> getWaypoint_order() {
return waypoint_order;
}
public void setWaypoint_order(ArrayList<String> waypoint_order) {
this.waypoint_order = waypoint_order;
}
public ArrayList<Legs> getLegs() {
return legs;
}
public void setLegs(ArrayList<Legs> legs) {
this.legs = legs;
}
public ArrayList<String> getWarnings() {
return warnings;
}
public void setWarnings(ArrayList<String> warnings) {
this.warnings = warnings;
}
public Overview_polyline getOverview_polyline() {
return overview_polyline;
}
public void setOverview_polyline(Overview_polyline overview_polyline) {
this.overview_polyline = overview_polyline;
}
#Override
public String toString() {
return "ClassPojo [summary = " + summary + ", bounds = " + bounds + ", copyrights = " + copyrights + ", waypoint_order = " + waypoint_order + ", legs = " + legs + ", warnings = " + warnings + ", overview_polyline = " + overview_polyline + "]";
}
public class Bounds
{
private Southwest southwest;
private Northeast northeast;
public Southwest getSouthwest ()
{
return southwest;
}
public void setSouthwest (Southwest southwest)
{
this.southwest = southwest;
}
public Northeast getNortheast ()
{
return northeast;
}
public void setNortheast (Northeast northeast)
{
this.northeast = northeast;
}
#Override
public String toString()
{
return "ClassPojo [southwest = "+southwest+", northeast = "+northeast+"]";
}
public class Southwest
{
private String lng;
private String lat;
public String getLng ()
{
return lng;
}
public void setLng (String lng)
{
this.lng = lng;
}
public String getLat ()
{
return lat;
}
public void setLat (String lat)
{
this.lat = lat;
}
#Override
public String toString()
{
return "ClassPojo [lng = "+lng+", lat = "+lat+"]";
}
}
public class Northeast
{
private String lng;
private String lat;
public String getLng ()
{
return lng;
}
public void setLng (String lng)
{
this.lng = lng;
}
public String getLat ()
{
return lat;
}
public void setLat (String lat)
{
this.lat = lat;
}
#Override
public String toString()
{
return "ClassPojo [lng = "+lng+", lat = "+lat+"]";
}
}
}
public class Overview_polyline {
private String points;
public String getPoints() {
return points;
}
public void setPoints(String points) {
this.points = points;
}
#Override
public String toString() {
return "ClassPojo [points = " + points + "]";
}
}
public class Legs {
private Duration duration;
private Distance distance;
private End_location end_location;
private String start_address;
private String end_address;
private Start_location start_location;
private ArrayList<String> traffic_speed_entry;
private ArrayList<String> via_waypoint;
private ArrayList<Steps> steps;
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public Distance getDistance() {
return distance;
}
public void setDistance(Distance distance) {
this.distance = distance;
}
public End_location getEnd_location() {
return end_location;
}
public void setEnd_location(End_location end_location) {
this.end_location = end_location;
}
public String getStart_address() {
return start_address;
}
public void setStart_address(String start_address) {
this.start_address = start_address;
}
public String getEnd_address() {
return end_address;
}
public void setEnd_address(String end_address) {
this.end_address = end_address;
}
public Start_location getStart_location() {
return start_location;
}
public void setStart_location(Start_location start_location) {
this.start_location = start_location;
}
public ArrayList<String> getTraffic_speed_entry() {
return traffic_speed_entry;
}
public void setTraffic_speed_entry(ArrayList<String> traffic_speed_entry) {
this.traffic_speed_entry = traffic_speed_entry;
}
public ArrayList<String> getVia_waypoint() {
return via_waypoint;
}
public void setVia_waypoint(ArrayList<String> via_waypoint) {
this.via_waypoint = via_waypoint;
}
public ArrayList<Steps> getSteps() {
return steps;
}
public void setSteps(ArrayList<Steps> steps) {
this.steps = steps;
}
#Override
public String toString() {
return "ClassPojo [duration = " + duration + ", distance = " + distance + ", end_location = " + end_location + ", start_address = " + start_address + ", end_address = " + end_address + ", start_location = " + start_location + ", traffic_speed_entry = " + traffic_speed_entry + ", via_waypoint = " + via_waypoint + ", steps = " + steps + "]";
}
public class Duration {
private String text;
private String value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
return "ClassPojo [text = " + text + ", value = " + value + "]";
}
}
public class Start_location
{
private String lng;
private String lat;
public String getLng ()
{
return lng;
}
public void setLng (String lng)
{
this.lng = lng;
}
public String getLat ()
{
return lat;
}
public void setLat (String lat)
{
this.lat = lat;
}
#Override
public String toString()
{
return "ClassPojo [lng = "+lng+", lat = "+lat+"]";
}
}
public class End_location {
private String lng;
private String lat;
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
#Override
public String toString() {
return "ClassPojo [lng = " + lng + ", lat = " + lat + "]";
}
}
public class Distance {
private String text;
private String value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
return "ClassPojo [text = " + text + ", value = " + value + "]";
}
}
public class Steps
{
private String html_instructions;
private Duration duration;
private Distance distance;
private End_location end_location;
private Polyline polyline;
private Start_location start_location;
private String travel_mode;
public String getHtml_instructions ()
{
return html_instructions;
}
public void setHtml_instructions (String html_instructions)
{
this.html_instructions = html_instructions;
}
public Duration getDuration ()
{
return duration;
}
public void setDuration (Duration duration)
{
this.duration = duration;
}
public Distance getDistance ()
{
return distance;
}
public void setDistance (Distance distance)
{
this.distance = distance;
}
public End_location getEnd_location ()
{
return end_location;
}
public void setEnd_location (End_location end_location)
{
this.end_location = end_location;
}
public Polyline getPolyline ()
{
return polyline;
}
public void setPolyline (Polyline polyline)
{
this.polyline = polyline;
}
public Start_location getStart_location ()
{
return start_location;
}
public void setStart_location (Start_location start_location)
{
this.start_location = start_location;
}
public String getTravel_mode ()
{
return travel_mode;
}
public void setTravel_mode (String travel_mode)
{
this.travel_mode = travel_mode;
}
#Override
public String toString()
{
return "ClassPojo [html_instructions = "+html_instructions+", duration = "+duration+", distance = "+distance+", end_location = "+end_location+", polyline = "+polyline+", start_location = "+start_location+", travel_mode = "+travel_mode+"]";
}
public class Polyline
{
private String points;
public String getPoints ()
{
return points;
}
public void setPoints (String points)
{
this.points = points;
}
#Override
public String toString()
{
return "ClassPojo [points = "+points+"]";
}
}
}
}
}
}
Now to draw the route in between way-points you can use the below method -
private void setRoutePath(DirectionApiResponse directionObj){
gMap.clear();
addMarkers(localLeedsArrayList);
int count = 0;
ArrayList<LatLng> points = null;
DirectionApiResponse.Routes route = directionObj.getRoutes().get(0);
// Traversing through all the routes
for(DirectionApiResponse.Routes.Legs leg : route.getLegs()){
PolylineOptions lineOptions = new PolylineOptions();
points = new ArrayList<LatLng>();
Log.e("Route", leg.getStart_address()+" "+leg.getEnd_address());
// Fetching all the points in i-th route
//for(DirectionApiResponse.Routes.Legs.Steps step : leg.getSteps()){
for(int j=0;j<leg.getSteps().size();j++){
DirectionApiResponse.Routes.Legs.Steps step = leg.getSteps().get(j);
points.addAll(PolyUtil.decode(step.getPolyline().getPoints()));
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(20);
lineOptions.color(colors[count]);
Polyline polylineFinal = gMap.addPolyline(lineOptions);
count++;
}
Log.e("SouthWest",directionObj.getRoutes().get(0).getBounds().getSouthwest().getLat()+" "+directionObj.getRoutes().get(0).getBounds().getSouthwest().getLng());
Log.e("northeast",directionObj.getRoutes().get(0).getBounds().getNortheast().getLat()+" "+directionObj.getRoutes().get(0).getBounds().getNortheast().getLng());
/*LatLng lSouth = new LatLng(Double.valueOf(directionObj.getRoutes().get(0).getBounds().getSouthwest().getLat()),
Double.valueOf(directionObj.getRoutes().get(0).getBounds().getSouthwest().getLng()));
LatLng lNorth = new LatLng(Double.valueOf(directionObj.getRoutes().get(0).getBounds().getNortheast().getLat()),
Double.valueOf(directionObj.getRoutes().get(0).getBounds().getNortheast().getLng()));
LatLngBounds latLngBounds = new LatLngBounds(lNorth,lSouth);
gMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds,14));*/
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLocation.getLatitude(),mCurrentLocation.getLongitude()),15));
}
Here gMap is the google map object..
******* UPDATE Api Calling********
In order to call the api Create interface IApiMethods and put the code below -
#GET("json?origin=35.693391,51.424261&destination=35.692032,51.432715&waypoints=35.691997,51.432758")
Call<DirectionApiResponse> getDirectionWalking(#Query("key")String key);
you can change the co-ordinates accordingly
Now call the method below to call the api and get the DirectionApiResponse object
private void getDirection(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://maps.googleapis.com/maps/api/directions/")
.addConverterFactory(GsonConverterFactory.create())
.build();
IApiMethods service = retrofit.create(IApiMethods.class);
Call<DirectionApiResponse> directionApiResponseCall = service.getDirectionWalking("YOUR API KEY");
directionApiResponseCall.enqueue(new Callback<DirectionApiResponse>() {
#Override
public void onResponse(Call<DirectionApiResponse> call, Response<DirectionApiResponse> response) {
setRoutePath(response.body());
}
#Override
public void onFailure(Call<DirectionApiResponse> call, Throwable t) {
}
});
}
Finally add the following dependencies to the app's build.gradle file -
compile 'com.google.android.gms:play-services-maps:8.4.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
How to get the route
You might want to look at the Distance Matrix service: https://developers.google.com/maps/documentation/javascript/distancematrix
It gives you distances between a set of origins and destinations, and might help you with narrowing down options.
2. To Find the best route :
If using the web service, ensure you set optimize:true before listing your waypoints, and check the waypoint_order array.
http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false
If use the JS API, set optimizeWaypoints:true in your request.
3. To draw polyline with the latlongs you have
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = myMap.addPolyline(options);

Empty string when using GSON for Java -> JSon

Trying to convert a POJO to a Json representation , my output is quite surprising : empty !
Here the POJO class :
public class AccountDTO extends BasicDBObject {
/**
*
*/
public static final String COLLECTION_NAME = "account-data";
private static final long serialVersionUID = 1L;
private String customerFirstName;
private String customerLastName;
private long customerId;
private String IBAN;
private float balance;
private String accountCurrency;
public AccountDTO(Account account, Customer customer) {
super();
this.customerFirstName = customer.getFirstname();
this.customerLastName = customer.getLastname();
this.customerId = customer.getCustomerId();
this.IBAN = account.getIBAN();
this.balance = account.getBalance();
this.accountCurrency = account.getAccountCurrency();
}
public String getCustomerName() {
return customerFirstName;
}
public void setCustomerName(String customerName) {
this.customerFirstName = customerName;
}
public String getCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String customerLastName) {
this.customerLastName = customerLastName;
}
public long getCustomerId() {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
public String getIBAN() {
return IBAN;
}
public void setIBAN(String iBAN) {
IBAN = iBAN;
}
public float getBalance() {
return balance;
}
public void setBalance(float balance) {
this.balance = balance;
}
public String getCustomerFirstName() {
return customerFirstName;
}
public void setCustomerFirstName(String customerFirstName) {
this.customerFirstName = customerFirstName;
}
public String getAccountCurrency() {
return accountCurrency;
}
public void setAccountCurrency(String accountCurrency) {
this.accountCurrency = accountCurrency;
}
#Override
public String toString() {
return "AccountDTO [customerFirstName=" + customerFirstName + ", customerLastName=" + customerLastName
+ ", customerId=" + customerId + ", IBAN=" + IBAN + ", balance=" + balance + ", accountCurrency="
+ accountCurrency + "]";
}
}
The converter :
public abstract class AccountDTODigester {
public static String digestJavaToJson(AccountDTO dto){
Gson gson = new Gson();
String json = gson.toJson(dto);
return json;
}
}
Code with jackson :
public abstract class AccountDTODigester {
public static String digestJavaToJson(AccountDTO dto) throws JsonProcessingException{
ObjectMapper mapper = new ObjectMapper();
String jsonInString = new String();
jsonInString = mapper.writeValueAsString(dto);
return jsonInString;
}
}
And finnaly the runner :
public class DAOTest {
AccountDTO accountDTO;
#Before
public void initialize(){
Account account = new Account("FRkk BBBB BGGG GGCC CCCC CCCC CKK", 0, "euro");
Customer customer = new Customer("XXXXXX", "YYYYYY", 1, account);
this.accountDTO = new AccountDTO(account, customer);
}
#Test
public void toJson(){
Assert.assertNotEquals(AccountDTODigester.digestJavaToJson(accountDTO),new String("{}"));
}
Console output :
AccountDTO [customerFirstName=XXXXXX, customerLastName=YYYYYY, customerId=1, IBAN=FRkk BBBB BGGG GGCC CCCC CCCC CKK, balance=0.0, accountCurrency=euro]
{}
When I run the test, my json string is { }and my test is mark as failed.
Gson seems to ver very easy to use, I don't understand why I got this empty Json instead a String filled with a json representation of my AccountDTO object
Ok I found solution :
My JSON was null because extends BasicDBObject , the serialization seems to be jammed by this.
Still looking for a better explication, but now my json is ok.

How to parse nested JSON objects data?

I'm using volley and gson libs in my Android app which main purpose is to call to the server API and retrieve some data.
Everything works well, expect for nested JSON object data. I can't retrieve information (lat, lng) which are inside position object.
It throws an error:
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 99 path $.position and points out to deliveryResponse method.
Example of my JSON:
[{"number":18,"name":"John","address":"John Street.","position":{"lat":12.68300406,"lng":45.28001237},"status":"OPEN"},{"number":18,"name":"John","address":"John Street.","position":{"lat":12.68300406,"lng":45.28001237},"status":"OPEN",}]
deliveryResponse method:
#Override
protected void deliverResponse(JSONArray jsonArray) {
if (mListener != null && jsonArray != null) {
List<T> responseArray = new ArrayList<T>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject entry = jsonArray.getJSONObject(i);
T parsedResponse = new Gson().fromJson(entry.toString(), mClass);
if (parsedResponse != null) {
responseArray.add(parsedResponse);
}
} catch (JSONException e) {
Log.d(TAG, "Error parsing JSON Object: " + e.getMessage());
mListener.onResponse(jsonArray);
}
}
mListener.onGsonResponse(responseArray);
}
}
Object class:
public class Object {
private int number;
private String name;
private String address;
private List<PositionObj> position;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<PositionObj> getPosition() {
return position;
}
public void setPosition(List<PositionObj> position) {
this.position = position;
}
PositionObj class:
public class PositionObj {
private int lat;
private int lng;
public int getLat() {
return lat;
}
public void setLat(int lat) {
this.lat = lat;
}
public int getLng() {
return lng;
}
public void setLng(int lng) {
this.lng = lng;
}
What do you sugggest?
In your JSON, position is an object and not an array. So, in your class Object(weird name), change private List<PositionObj> position; by private PositionObj position;.

Categories

Resources