axios post request not mapping to java object property in Requestbody - json

I am working on a Java Spring boot application, with React JS as the front-end. In my react js project, on a form submit, I send data to the Spring API. For some reason, I am unable to map the javascript JSON array property to the java array property. All of the other String datatype properties match apart from the array. This is my example, on the react js front-end.
export function addBooking(bookings) {
return new Promise((resolve, reject) => {
axios.post(url, bookings)
.then((response) => {
resolve(response.data);
})
.catch((error) => {
reject(error);
});
});
}
Above is my react code which sends this JSON object, below.
{
"street": "someStreet",
"city": "somecity",
"contactNumber" : "0000",
“piecesData”: [
{
“id”: “111“,
“weight”: “22”,
“length”: “32”,
“width”: “23”,
“height”: “23”
“type”: “heavyLoad”
},
{
“id”: “111“,
“weight”: “22”,
“length”: “32”,
“width”: “23”,
“height”: “23”
“type”: “heavyLoad”
}
]
}
For some reason on the Spring server side the only properties that get mapped are street, city and contactNumber. However, the piecesData does not get mapped to it's corresponding java array property.
This is the Java model object:
public class Test implements Serializable{
public String city;
public String street;
public String contactNumber;
#OneToMany(
cascade = {CascadeType.ALL},
fetch = FetchType.EAGER
)
#JoinColumn(name = "booking_id", referencedColumnName = "booking_id")
public PieceData[] pieceData;
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public PieceData[] getPieceData() {
return pieceData;
}
public void setPieceData(PieceData[] pieceData) {
this.pieceData = pieceData;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
contactNumber = contactNumber;
}
}
Once I am able to get all of this data then I wish to be able to save a Booking and it's pieceDatas array into the Database using JPA.
Below is my java PieceData object:
#Entity
#Table(name="pieceData")
public class PieceData implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String weight;
private String length;
private String width;
private Integer height;
private Integer booking_id;
public Integer getBooking_id() {
return this.booking_id;
}
public void setBooking_id(Integer booking_id) {
this.booking_id = booking_id;
}
public PieceData() {
}
public PieceData(Integer height, String length, String width, String weight) {
this.length = length;
this.width = width;
this.weight = weight;
this.height = height;
}
// Weight
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
// Length
public String getLength() {
return length;
}
public void setLength(String length) {
this.length = length;
}
// Width
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
// Height
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
}

I solved my answer by adding the json property annotation to the List pieceData type:
#JsonProperty(value = "piecesData")
private List<PieceData> piecesDatas;

Related

javax.ejb.EJBException: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

GSON Throwing Syntax exception While parsing the JSON into a Java Objects. Here I have attached my JSON and the Classes by which JSON has been parsed and the code where I am parsing the JSON values. Please help me to fix this error.
The following is my JSON Response Which is to be parsed.
JSON
[
{ "counter":1,
"data":{
"b":[
{"d":11.080666011022274,"e":-9.84375},
{"d":21.36033117555945,"e":-13.18359375},
{"d":25.55169302685644,"e":-5.09765625},
{"d":20.209969075006228,"e":24.9609375},
{"d":6.740259027196141,"e":27.7734375},
{"d":19.38301389529031,"e":10.01953125}
],
"gm_accessors_":{"length":null},
"length":6,
"gm_bindings_":{"length":{}}
}
},
{ "counter":2,
"data":{
"b":[
{"d":43.76263306667474,"e":60.1171875},
{"d":56.310038487065135,"e":47.8125},
{"d":60.881999484084055,"e":78.22265625},
{"d":55.81939178481952,"e":96.6796875},
{"d":44.76961886697326,"e":99.84375},
{"d":55.72051189919337,"e":82.08984375},
{"d":40.50489156437503,"e":81.5625},
{"d":52.74250152629922,"e":72.0703125}
],
"gm_accessors_":{"length":null},
"length":8,
"gm_bindings_":{"length":{}}
}
}
]
The Above Json has been parsed by the following JAVA classes. In the following Class structure I am making Mistake. Please guide me where I am doing the mistake.
**Parent Class -- SHAPE**
public class Shape {
#SerializedName("counter")
private Integer mCounter;
#SerializedName("data")
private Data mData;
public Data getmData() {
return mData;
}
public void setmData(Data mData) {
this.mData = mData;
}
public Integer getCounter() {
return mCounter;
}
public void setCounter(Integer counter) {
this.mCounter = counter;
}
}
**CHILD CLASS -- DATA**
public class Data {
#SerializedName("length")
private Integer length;
#SerializedName("b")
private b mCoordinates;
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public b getmCoordinates() {
return mCoordinates;
}
public void setmCoordinates(b mCoordinates) {
this.mCoordinates = mCoordinates;
}
}
**GRAND CHILD CLASS -- b**
public class b {
#SerializedName("d")
private ArrayList<Float> lattitude;
#SerializedName("e")
private ArrayList<Float> longtitude;
public ArrayList<Float> getLattitude() {
return lattitude;
}
public void setLattitude(ArrayList<Float> lattitude) {
this.lattitude = lattitude;
}
public ArrayList<Float> getLongtitude() {
return longtitude;
}
public void setLongtitude(ArrayList<Float> longtitude) {
this.longtitude = longtitude;
}
}
JSON PARSING -- CHANGING JSON AS A JAVA OBJECTS
JsonParser parser = new JsonParser();
JsonArray jArray = parser.parse(jsonContent).getAsJsonArray();
System.out.println("Array :_: " + jArray);
for(JsonElement jsonElement : jArray) {
System.out.println("JSON_ELEMENT :_: " + jsonElement);
Shape shape = gson.fromJson(jsonElement, Shape.class);
System.out.println("Counter :_: " + shape.getCounter());
}
Please chnage your data class to :
public class Data {
#SerializedName("length")
private Integer length;
#SerializedName("b")
// this is where the error was thrown,
// it was expecting an array but only received a single object.
private List<b> mCoordinates;
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public List<b> getmCoordinates() {
return mCoordinates;
}
public void setmCoordinates(List<b> mCoordinates) {
this.mCoordinates = mCoordinates;
}
}
And also change the b class to:
public class b {
#SerializedName("d")
private double d;
#SerializedName("e")
private double e;
public double getD() {
return d;
}
public void setD(double d) {
this.d = d;
}
public double getE() {
return e;
}
public void setE(double e) {
this.e = e;
}
}
use:
Gson gson = new Gson();
Shape shape = gson.fromJson(reader/string here, Shape.class);
and your shape class will be filled.
public class Shape {
#SerializedName("counter")
private Integer mCounter;
#SerializedName("data")
private Data mData;
// geter/setter here
}
public class Data {
#SerializedName("length")
private Integer length;
#SerializedName("b")
private List<Coordinate> coordinates;
#SerializedName("gm_accessors_")
private Accessors gmAccessors;
//getter setter here
}
public class Coordinate {
private float d;
private float e;
}
public class Accessors {
private Integer length;
}
Finally Parse it as
Shape[] shapes = gson.fromJson(jArray, Shape[].class);
If you will parse like this you will get same error : Expected BEGIN_OBJECT but was BEGIN_ARRAY
Shape shape = gson.fromJson(jArray, Shape.class);

dropwizard: incorrect json resulting from group of items

I am using Dropwizard to deliver a RESTful service. The JSON I EXPECT looks like this:
{"featuredMerchants":
{"featuredMerchant":[
{"browseId":"v1_0_0_1112",
"merchantId":3902,
"priority":1,
"sourceId":"15"},
...,
{"browseId":"v1_0_0_1112",
"merchantId":456,
"priority":4,
"sourceId":"15"}]}}
But the JSON I am GETTING is this:
{"featuredMerchant":[
{"browseId":"v1_0_0_1112",
"merchantId":3902,
"priority":1,
"sourceId":"15"},
...,
{"browseId":"v1_0_0_1112",
"merchantId":456,
"priority":4,
"sourceId":"15"}]}
I have two classes. I have an ApiFeaturedMerchantGroup class that contains a list of ApiFeaturedMerchants.
#JsonRootName("featuredMerchants")
public class ApiFeaturedMerchantGroup {
private List<ApiFeaturedMerchant> apiFeaturedMerchants;
public ApiFeaturedMerchantGroup() {
}
#JsonProperty("featuredMerchant")
public List<ApiFeaturedMerchant> getApiFeaturedMerchants() { return apiFeaturedMerchants; }
public void setApiFeaturedMerchants(List<ApiFeaturedMerchant> apiFeaturedMerchants) { this.apiFeaturedMerchants = apiFeaturedMerchants; }
}
#JsonRootName("featuredMerchant")
public class ApiFeaturedMerchant {
private String browseId;
private int merchantId;
private Integer priority;
private String sourceId;
public ApiFeaturedMerchant() {
}
public String getBrowseId() { return browseId; }
public void setBrowseId(String browseId) { this.browseId = browseId; }
public int getMerchantId() { return merchantId; }
public void setMerchantId(int merchantId) { this.merchantId = merchantId; }
public Integer getPriority() { return priority; }
public void setPriority(Integer priority) { this.priority = priority; }
public String getSourceId() { return sourceId; }
public void setSourceId(String sourceId) { this.sourceId = sourceId; }
}
How do I get the extra level into my JSON, the "featuredMerchants" group that contains the individual "featuredMerchant" items? Do I have the wrong annotations, or am I missing one/some?
It's a setting on ObjectMapperFactory:
ObjectMapperFactory objectMapperFactory = new ObjectMapperFactory();
objectMapperFactory.enable(SerializationFeature.WRAP_ROOT_VALUE);
objectMapper = objectMapperFactory.build();

Create JSON using GSON with a colon as part of a field's name

I've created a set of classes (pojos) that need to be transformed into json. because i have a constraint that json field names adhere to a certain format, i've settled on gson as my library of choice, as it allows for annotations of field names.
so, i have json field names like asset_type, preview_image_thumbnail, etc. along with that, any metadata fields must have the format, metadata:<metadata-field-name>.
so, what this comes down to is that my metadata:tags and metadata:site annotations will not be transformed by gson, since they are not valid json field names, according to gson, at least.
all works well, except for those darned metadata field names. my goal is to have output like the following:
{
"name": "Test Remote Asset",
"description": "test-remote-asset",
"asset_type": "remote_asset",
"duration": 172360,
"stream_urls": {
"flash": "http://www.test-site.com/videos/a-video.flv",
"iphone": "http://www.test-site.com/videos/a-video.3gp",
"ipad": "http://www.test-site.com/videos/a-video.3gp",
"source_file": "http://www.test-site.com/videos/a-video.mp4"
},
"metadata:tags": "tag1,tag2,tag3",
"metadata:site": "test-site"
}
here is the exception i get when attempting to transform my class to json:
java.lang.IllegalArgumentException: metadata:tags is not a valid JSON field name.
and here is the class i want to transform:
public class RemoteAsset {
/** The video's name **/
private String name;
/** The video's description **/
private String description;
/** The video asset type **/
#SerializedName("asset_type")
private String assetType;
/** The video's duration, in milliseconds **/
private long duration;
/** The video's thumbnail preview URL **/
#SerializedName("preview_image_url")
private String previewImageUrl;
/** The video's OpenCms Structure ID **/
#SerializedName("external_id")
private String externalId;
/** The video's various streaming URLs **/
#SerializedName("stream_urls")
private StreamUrls streamUrls;
/** The video's tags, coma-separated **/
#SerializedName("metadata:tags")
private String metadataTags;
/** The video's host site **/
#SerializedName("metadata:site")
private String metadataSite;
public String getMetadataTags() {
return metadataTags;
}
public void setMetadataTags(String metadata_tags) {
this.metadataTags = metadata_tags;
}
public String getMetadataSite() {
return metadataSite;
}
public void setMetadataSite(String metadata_site) {
this.metadataSite = metadata_site;
}
public RemoteAsset() {
this.streamUrls = null;
this.assetType = null;
this.previewImageUrl = "";
this.metadataSite = "";
this.metadataTags = "";
this.externalId = "";
this.description = "";
this.duration = 0L;
this.name = "";
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAssetType() {
return this.assetType;
}
public void setAssetType(ASSET_TYPE asset_type) {
this.assetType = asset_type.getTypeName();
}
public long getDuration() {
return this.duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public String getPreviewImageUrl() {
return this.previewImageUrl;
}
public void setPreviewImageUrl(String preview_image_url) {
this.previewImageUrl = preview_image_url;
}
public String getExternalId() {
return this.externalId;
}
public void setExternalId(String external_id) {
this.externalId = external_id;
}
public StreamUrls getStreamUrls() {
return this.streamUrls;
}
public void setStreamUrls(StreamUrls stream_urls) {
this.streamUrls = stream_urls;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RemoteAsset [name=").append(this.name)
.append(", description=").append(this.description)
.append(", assetType=").append(this.assetType)
.append(", duration=").append(this.duration)
.append(", previewImageUrl=").append(this.previewImageUrl)
.append(", externalId=").append(this.externalId)
.append(", streamUrls=").append(this.streamUrls).append("]");
return builder.toString();
}
}
The problem is that those can't be mapped directly to Java variables because you can't have a colon in a variable name. You need to use the Gson #SerializedName annotation. The following works at least in Gson version 2.2.2:
public static void main( String[] args )
{
String json = "{\"some:field\":\"foo\"}";
Gson gson = new Gson();
MyClass mc = gson.fromJson(json, MyClass.class);
json = gson.toJson(mc);
System.out.println(json);
}
class MyClass
{
// String some:field; <- You can do that!
#SerializedName("some:field")
String someField;
}
Output:
{"some:field":"foo"}

How can I deseralize json object in java pojo class?

I have a simple JSON statement which type is very per need. like this
{
actor:{name:"kumar",mbox:"kumar#gmail.com"}
verb :"completed"
}
or
{
actor:{name:["kumar","manish"],mbox:["kumar#gmail.com","manish#gmail.com"]}
verb :{
"id" : "http://adlnet.gov/expapi/verbs/completed",
"display" : {
"en-US" : "completed"
}
}
I am using using POJO class to map this json string and pojo class code is given bleow
#JsonProperty("actor")
Actor actor;
#JsonProperty("verb")
Verb objVerb;
#JsonProperty("verb")
String verb;
public Actor getActor() {
return actor;
}
public void setActor(Actor actor) {
this.actor = actor;
}
public Verb getObjVerb() {
return objVerb;
}
public void setObjVerb(Verb objVerb) {
this.objVerb = objVerb;
}
#JsonIgnore
public String getVerb() {
return verb;
}
#JsonIgnore
public void setVerb(String verb) {
this.verb = verb;
}
public static class Actor {
String objectType;
#JsonProperty("name")
ArrayList<String> listName;
#JsonProperty("name")
String name;
#JsonProperty("mbox")
ArrayList<String> listMbox;
#JsonProperty("mbox")
String mbox;
#JsonProperty("mbox_sha1sum")
ArrayList<String> Listmbox_sha1sum;
#JsonProperty("mbox_sha1sum")
String mbox_sha1sum;
#JsonProperty("openid")
String openid;
#JsonProperty("account")
Account account;
public String getObjectType() {
return objectType;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
public ArrayList<String> getListName() {
return listName;
}
public void setListName(ArrayList<String> listName) {
this.listName = listName;
}
#JsonIgnore
public String getName() {
return name;
}
#JsonIgnore
public void setName(String name) {
this.name = name;
}
public ArrayList<String> getListMbox() {
return listMbox;
}
public void setListMbox(ArrayList<String> listMbox) {
this.listMbox = listMbox;
}
#JsonIgnore
public String getMbox() {
return mbox;
}
#JsonIgnore
public void setMbox(String mbox) {
this.mbox = mbox;
}
public ArrayList<String> getListmbox_sha1sum() {
return Listmbox_sha1sum;
}
public void setListmbox_sha1sum(ArrayList<String> listmbox_sha1sum) {
Listmbox_sha1sum = listmbox_sha1sum;
}
#JsonIgnore
public String getMbox_sha1sum() {
return mbox_sha1sum;
}
#JsonIgnore
public void setMbox_sha1sum(String mbox_sha1sum) {
this.mbox_sha1sum = mbox_sha1sum;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public static class Account {
#JsonProperty("homePage")
String homePage;
#JsonProperty("name")
String name;
public String getHomePage() {
return homePage;
}
public void setHomePage(String homePage) {
this.homePage = homePage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
public static class Verb {
String id;
Map<String,String> display;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, String> getDisplay() {
return display;
}
public void setDisplay(Map<String, String> display) {
this.display = display;
}
}
I am using jaxb and jakson. I am implementing the webservice to handle the json statement
so I use the bean class to map with json. But when I use to map this json then it gives the following exceptions
org.codehaus.jackson.map.JsonMappingException : property with the name "mbox" have two entry.
Define a proper bean structure so it directly mapped to the beans class
Try to leave only #JsonProperty("mbox") ArrayList<String> listMbox; field (don't need #JsonProperty("mbox")
String mbox;)
and add Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY=true to Jackson object mapper config.
So in deserialization it will be able to get as both array and single element.
you can use gson.
class cls = gson.fromJson(jsonString, clazz);
here jsonString can be stringified java script object. gson.fromJson method can map your java script key to java property.

how to parse this json response?

i know how to parse response like {\"screenTitle\":\"National Geographic\"}
token.optString("screenTitle"); up to this ok.
but see this response
{
"status": "OK",
"routes": [ {
"summary": "Southern Exp",
"legs": [ {
"steps": [ {
"travel_mode": "DRIVING",
"start_location": {
"lat": -34.9257700,
"lng": 138.5997300
},
"end_location": {
"lat": -34.9106200,
"lng": 138.5991300
},
i want the lat and long value.
how can i achive this.
Here's a quick code to get latitude and longitude of start_location in the following path
routes[0]/legs[0]/steps[0]/start_location:
JSONObject obj = new JSONObject(source.toString());
JSONObject startLoaction = obj.getJSONArray("routes")
.getJSONObject(0).getJSONArray("legs")
.getJSONObject(0).getJSONArray("steps")
.getJSONObject(0).getJSONObject("start_location");
System.out.println(
startLoaction.get("lat") + ", " + startLoaction.get("lng")
);
This code is just to give you an idea as to how to parse objects in JSON deep down. You may want to write a generic path like query mechanism (think XPath-like) for JSON objects, which will give you objects based on query inside a JSON
e.g. In your case:
JSONObject startLocation = JSONFinder.query(
"/routes[0]/legs[0]/steps[0]/start_location", sourceJSONObject)
Nothing will be able to parse the string that you've provided, because it has syntax errors.
However, this is JSON. Follow the instructions of your favourite tool that supports JSON in Java.
Are you able to provide the exception that is being raised? Then I could write something more specific.
Use Following depedency
<!-- json -->
<dependency>
<groupId>com.google.code.geocoder-java</groupId>
<artifactId>geocoder-java</artifactId>
<version>0.9</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
Use following Code in your main method
public static void main(String[] args) {
try {
String point = "your json response";
Gson gson = new Gson();
TypeToken<RoutePlot> tokenPoint = new TypeToken<RoutePlot>() {
};
RoutePlot user = gson.fromJson(point, tokenPoint.getType());
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
}
Now use the following classes , i have generated for response to map into java
package com.admin.modules.restservices.google.pojo.routepojo;
public class Bounds {
private Northeast northeast;
private Southwest southwest;
public Northeast getNortheast() {
return northeast;
}
public void setNortheast(Northeast northeast) {
this.northeast = northeast;
}
public Southwest getSouthwest() {
return southwest;
}
public void setSouthwest(Southwest southwest) {
this.southwest = southwest;
}
}
package com.admin.modules.restservices.google.pojo.routepojo;
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;
}
}
package com.admin.modules.restservices.google.pojo.routepojo;
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;
}
}
package com.admin.modules.restservices.google.pojo.routepojo;
public class Endlocation {
private String lat;
private String lng;
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
}
package com.admin.modules.restservices.google.pojo.routepojo;
import java.util.List;
public class Legs {
private Distance distance;
private Duration duration;
private String end_address;
private Endlocation end_location;
private String start_address;
private Startlocation start_location;
private List<Steps> steps;
private List<String> via_waypoint;
public List<String> getVia_waypoint() {
return via_waypoint;
}
public void setVia_waypoint(List<String> via_waypoint) {
this.via_waypoint = via_waypoint;
}
public Distance getDistance() {
return distance;
}
public void setDistance(Distance distance) {
this.distance = distance;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public String getEnd_address() {
return end_address;
}
public void setEnd_address(String end_address) {
this.end_address = end_address;
}
public Endlocation getEnd_location() {
return end_location;
}
public void setEnd_location(Endlocation 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 Startlocation getStart_location() {
return start_location;
}
public void setStart_location(Startlocation start_location) {
this.start_location = start_location;
}
public List<Steps> getSteps() {
return steps;
}
public void setSteps(List<Steps> steps) {
this.steps = steps;
}
}
package com.admin.modules.restservices.google.pojo.routepojo;
public class Northeast {
private String lat;
private String lng;
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
}
package com.admin.modules.restservices.google.pojo.routepojo;
public class Overviewpolyline {
}
package com.admin.modules.restservices.google.pojo.routepojo;
public class Polyline {
private String points;
public String getPoints() {
return points;
}
public void setPoints(String points) {
this.points = points;
}
}
package com.admin.modules.restservices.google.pojo.routepojo;
import java.util.List;
public class RoutePlot {
private String status;
private List<Routes> routes;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<Routes> getRoutes() {
return routes;
}
public void setRoutes(List<Routes> routes) {
this.routes = routes;
}
}
package com.admin.modules.restservices.google.pojo.routepojo;
import java.util.List;
public class Routes {
private Bounds bounds;
private String copyrights;
private List<Legs> legs;
private Overviewpolyline overview_polyline;
private String summary;
private List<String> warnings;
private List<String> waypoint_order;
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 List<Legs> getLegs() {
return legs;
}
public void setLegs(List<Legs> legs) {
this.legs = legs;
}
public Overviewpolyline getOverview_polyline() {
return overview_polyline;
}
public void setOverview_polyline(Overviewpolyline overview_polyline) {
this.overview_polyline = overview_polyline;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public List<String> getWarnings() {
return warnings;
}
public void setWarnings(List<String> warnings) {
this.warnings = warnings;
}
public List<String> getWaypoint_order() {
return waypoint_order;
}
public void setWaypoint_order(List<String> waypoint_order) {
this.waypoint_order = waypoint_order;
}
}
package com.admin.modules.restservices.google.pojo.routepojo;
public class Southwest {
private String lat;
private String lng;
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
}
package com.admin.modules.restservices.google.pojo.routepojo;
public class Startlocation {
private String lat;
private String lng;
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
}
package com.admin.modules.restservices.google.pojo.routepojo;
import java.util.List;
public class Steps {
private Distance distance;
private Duration duration;
private Endlocation end_location;
private Startlocation start_location;
private String html_instructions;
private String travel_mode;
private Polyline polyline;
}
Ok, seeing that you have a JSON string (and you're possibly using JSON from here), if you want to return an array from JSON, do something like this:
JSONArray array = json.getJSONArray("routes");
Edit To get Geo-location, you will have to iterate through the array. In this example, I've taken the value from routs[0]/legs[0]/steps[0]/start_location
JSONArray array = json.getJSONArray("routes");
for (int i = 0; i < array.length(); i++) {
JSONObject subJson = array.getJSONObject(i); //Assuming that in the array there's ONLY JSON objects
JSONArray legs = subJson.getJSONArray("legs");
//Now for legs, you can iterate through it but I don't know how your JSON structure is so
//I didn't do it here.
JSONArray steps = legs.getJSONObject(0).getJSONArray("steps");
JSONObject startLocation = steps.getJSONObject(0).getJSONObject("start_location");
double lat = startLocation.getDouble("lat");
double lng = startLocation.getDouble("lng");
}