Exception : java.util.LinkedHashMap cannot be cast to com.excel.entity.ClassA - mysql

This is the generic method through which i am accepting list of
objects and downcasting to a specific object
public Response generate(List<?> list){
List<ClassA> List1 = new ArrayList<ClassA>();
List<ClassB> List2 = new ArrayList<ClassB>();
List<ClassC> List3 = new ArrayList<ClassC>();
if(list instanceof List<?>){
List1=(List<ClassA>) list;//in this line i am getting error
addDataToExcel(List1);
}
else if(list instanceof List<?>){
List2=(List<ClassB>) list;
addDataToExcel(List1);
}
else if(list instanceof List<?>){
List3=(List<ClassC>) list;
addDataToExcel(List1);
}
This is classA
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
#Entity
#Table(name="ClassA")
public class ClassA {
#Id
#Column(name="rollNo")
private int rollNo;
#Column(name="name")
private String name;
#Column(name="english")
private double english;
#Column(name="maths")
private double maths;
#Column(name="science")
private double science;
#Column(name="totalMarks")
private double totalMarks;
#Column(name="percentage")
private double percentage;
#Column(name="status")
private boolean status;
#Lob
#Column(name="file", columnDefinition="BLOB")
private byte[] file;
public ClassA() {
// TODO Auto-generated constructor stub
}
public ClassA(int rollNo, String name, double english, double maths, double science, double totalMarks,
double percentage, boolean status, byte[] file) {
super();
this.rollNo = rollNo;
this.name = name;
this.english = english;
this.maths = maths;
this.science = science;
this.totalMarks = totalMarks;
this.percentage = percentage;
this.status = status;
this.file = file;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getEnglish() {
return english;
}
public void setEnglish(double english) {
this.english = english;
}
public double getMaths() {
return maths;
}
public void setMaths(double maths) {
this.maths = maths;
}
public double getScience() {
return science;
}
public void setScience(double science) {
this.science = science;
}
public double getTotalMarks() {
return totalMarks;
}
public void setTotalMarks(double totalMarks) {
this.totalMarks = totalMarks;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public byte[] getFile() {
return file;
}
public void setFile(byte[] file) {
this.file = file;
}
}
This is the method which accepts List and generate excel
public void add(List<ClassA> classA) {
System.out.println("entering add");
String excelFilePath = "D:/eclipse_neon/StudentInfo.xlsx";
try {
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowNum = 1;
int a=2;
for(ClassA info: classA){
System.out.println("netering loop");
Row row = sheet.getRow(rowNum++);
row.createCell(2).setCellValue(info.getEnglish());
row.createCell(3).setCellValue(info.getMaths());
row.createCell(4).setCellValue(info.getScience());
row.createCell(5).setCellFormula("SUM(C"+a+","+"D"+a+","+"E"+a+")");
row.createCell(6).setCellFormula("("+"F"+a+"*"+"100"+")"+"/"+"300");
row.createCell(7).setCellValue(info.isStatus());
a++;
}
System.out.println("after for loop");
inputStream.close();
FileOutputStream outputStream = new FileOutputStream("D:/eclipse_neon/StudentInfo.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException | EncryptedDocumentException
| InvalidFormatException ex) {
ex.printStackTrace();
}
}
I am not able to downcast to my specific List of class from generic list soo any suggestions are welcomed Thankyou

That's probably because you're sending a list as parameter containing a List and class A is not related to LinkedHashMap (not a subclass for example) and therefore it cannot cast. If you can provide more details what is class A and what is the list you're sending as arguments to your method.
Check https://www.baeldung.com/java-type-casting

Related

Evaluate expression json result In debug mode is different with final json result

I have a controller like this:
#ResponseBody
#RequestMapping(value = "/getLayersOfCategory/{categoryId}", method = RequestMethod.GET)
public LayersResult GetLayersOfCategory(#PathVariable("categoryId") Integer categoryId,#RequestHeader("secret") String secret) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm");
DataServicesModel dataServicesModel=new DataServicesModel();
LocalDateTime now = LocalDateTime.now();
CategoriesEntity categoriesEntity=new CategoriesEntity();
categoriesEntity.setId(categoryId);
List<Object[]> layersCategoriesEntityList=layersCategoriesRepository.findAllByCategoryId(categoryId);
List<String> stringList=new ArrayList<>();
for (Object[] row:layersCategoriesEntityList){
stringList.add(row[2].toString());
}
LayersResult layersResult=this.GetPoints(stringList);
**** return layersResult;
}
at **** when I Evaluate "layersResult" expression it shows a json like this:
but when I call the controller by postman
I get something like this:
as you see the iconUrl key has different. I do not know wher the result change at the end of the controller without any line of code tha could change the final result.
thanks in advance for replying.
And this a DataLayerModel:
package org.rajman.lbs.neshan.business.data.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParseException;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import javax.persistence.*;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class DataLayerModel {
private Integer id;
private String title;
private String type;
private String iconUrl="kdjjfhskdjfh";
private String webUrl="http://map.tabr*.ir";
#JsonIgnore
public String getStyle() { return style;
}
public void setStyle(String style) {
this.style = style;
}
private String style="{\"icon\":\"dt.png\"}";
#Value("${url.webUrl:#{null}}")
#JsonIgnore
public String getWebUrl() {
return webUrl;
}
public void setWebUrl(String webUrl) {
this.webUrl = webUrl;
}
public DataLayerModel() {
}
public DataLayerModel(Integer id, String title, String type, String style) {
this.id = id;
this.title = title;
this.type = type.equals("ST_Polygon") || type.equals("polygon") ? "polygon" : "point";
this.style=style;
//this.iconUrl = getIconUrl();
}
public String getIconUrl() {
Object icon;
String url="";
JSONObject jsonObject;
try {
url=this.style;
jsonObject = new JSONObject(this.style);
icon=jsonObject.get("icon");
url=this.getWebUrl()+"/images/"+icon.toString();
}
catch (Exception e){
System.out.println(e);
}
return url;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Assuming iconUrl is a String. i.e. serialization is straight forward.
The only thing, I can guess that would go wrong is getIconUrl() method.
Please try to evaluate, layers.get(0).getIconUrl() at the same debug point.

Jackson JSON Can not construct instance of "About" : deserialize issue

I've make HttpsURLConnection to receive some information about my server.
The result of response is :
{"about":{"title":"NiFi","version":"1.1.0","uri":"https://localhost:443/api/","contentViewerUrl":"/nifi-content-viewer/","timezone":"CET"}}
How is possible to extract all attributes and key/value ?
About.class file
public class About {
private List<AboutObject> about;
public About()
{
// this.about = about;
}
public List<AboutObject> getAbout() {
return this.about;
}
public void setAbout(List<AboutObject> about) {
this.about = about;
}
}
AboutObject.class
public class AboutObject {
private String title;
private String uri;
private String contentViewerUrl;
private String timezone;
public String getTitle()
{
return this.title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getUri()
{
return this.uri;
}
public void setUri(String uri)
{
this.uri = uri;
}
public String getContentViewerUrl()
{
return this.contentViewerUrl;
}
public void setContentViewerUrl(String contentViewerUrl)
{
this.contentViewerUrl = contentViewerUrl;
}
public String getTimeZone()
{
return this.timezone;
}
public void setTimeZone(String timezone)
{
this.timezone = timezone;
}
}
Main.class
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
System.out.println("Contenu de in = " + in.toString());
ObjectMapper mapper = new ObjectMapper();
//Staff objStaff = new Staff();
System.out.println("Object to JSON in file");
mapper.writeValue(new File("output/file.json"), response);
System.out.println("Convert JSON string from file to Object");
//String about = mapper.readValue(new File("output/file.json"), String.class);
About about = mapper.readValue(new File("output/file.json"), About.class);
Error
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of About: no String-argument constructor/factory method to deserialize from String value ('{"about":{"title":"NiFi","version":"1.1.0","uri":"https://localhost:443/api/","contentViewerUrl":"/nifi-content-viewer/","timezone":"CET"}}') at [Source: output/file.json; line: 1, column: 1]
Thanks for you help
The test json you show doesn't have the array wrapper used in your About object. You're also missing the version field in your AboutObject and the timezone field uses the wrong case.
Your example worked when I updated your objects:
public class About {
private AboutObject about;
public AboutObject getAbout() {
return about;
}
public void setAbout(AboutObject about) {
this.about = about;
}
}
public class AboutObject {
private String title;
private String uri;
private String contentViewerUrl;
private String timezone;
private String version;
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUri() {
return this.uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getContentViewerUrl() {
return this.contentViewerUrl;
}
public void setContentViewerUrl(String contentViewerUrl) {
this.contentViewerUrl = contentViewerUrl;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
Test:
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String obj = "{\"about\":{\"title\":\"NiFi\",\"version\":\"1.1.0\",\"uri\":\"https://localhost:443/api/\",\"contentViewerUrl\":\"/nifi-content-viewer/\",\"timezone\":\"CET\"}}";
About about = mapper.readValue(obj, About.class);
}

Issue with deserializing nested json

I am working on deserializing the below JSON:
{"self":"http://members.cs.com/rest/api/user?username=abc#cs.com",
"key":"abc#cs.com",
"name":"abc#cs.com",
"emailAddress":"abc#cs.com",
"displayName":"ABC",
"active":true,
"members":{"size":1,"items":[{"name":"member-users","self":"http://members.cs.com/rest/api/user?username=abc#cs.com"}]},
"expand":"members"}
I have created the following classes:
#JsonIgnoreProperties(ignoreUnknown = true)
public class UserList {
private String name;
private String emailAddress;
private String displayName;
private boolean active;
List<MemberName> members = new ArrayList<>();
#JsonCreator
public UserList(#JsonProperty("name") String name, #JsonProperty("emailAddress") String emailAddress, #JsonProperty("displayName") String displayName, #JsonProperty("active") boolean active, #JsonProperty("members") List<MemberName> members) {
this.name = name;
this.emailAddress = emailAddress;
this.displayName = displayName;
this.active = active;
this.members.addAll(groups);
}
//getters
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class MemberName {
private String name;
#JsonCreator
public MemberName(#JsonProperty("name") String name) {
this.name = name;
}
public String getName() {
return name;
}
}
When I don't give the members as a property the deserialization works fine and I can see the values for the name, displayName, active, emailAddress. The problem happens with the MemberName.
Could someone help with this?
This worked for me:
Class Items as below:
public class Items {
private String name;
private String self;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
}
Members class as below:
public class Members {
private int size;
private List<Items> items;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public List<Items> getItems() {
return items;
}
public void setItems(List<Items> items) {
this.items = items;
}
}
Data class as below:
public class Data {
private String self;
private String key;
private String name;
private String emailAddress;
private String displayName;
private boolean active;
private Members members;
private String expand;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Members getMembers() {
return members;
}
public void setMembers(Members members) {
this.members = members;
}
public String getExpand() {
return expand;
}
public void setExpand(String expand) {
this.expand = expand;
}
}
The deserialization as below:
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String jsonString = "{\"self\": \"http://members.cs.com/rest/api/user?username=abc#cs.com\",\"key\": \"abc#cs.com\",\"name\": \"abc#cs.com\","
+ "\"emailAddress\": \"abc#cs.com\",\"displayName\": \"ABC\",\"active\": true,\"members\": {\"size\": 1,\"items\": [{"
+ "\"name\": \"member-users\",\"self\": \"http://members.cs.com/rest/api/user?username=abc#cs.com\" }]},\"expand\": \"members\"}";
ObjectMapper mapper = new ObjectMapper();
Data obj = mapper.readValue(jsonString,Data.class);
System.out.println(obj.getSelf());
System.out.println(obj.getKey());
System.out.println(obj.getName());
System.out.println(obj.getEmailAddress());
System.out.println(obj.getDisplayName());
System.out.println(obj.isActive());
System.out.println(obj.getMembers().getSize());
System.out.println(obj.getMembers().getItems().get(0).getName());
System.out.println(obj.getMembers().getItems().get(0).getSelf());
System.out.println(obj.getExpand());
}

how to create a manytomany relationship between an entity and org.hibernate.usertype.UserType

I have an entity like this:
#Entity
#Table(name = "PLATFORM")
public class Platform{
#Id
#Column(name = "PLATFORM_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer platformId;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="PLATFORM_TYPE_ID")
private PlatformType platformType;
//must be manytomany but how?
private List<MimeType> supportedMimeTypes;
...
And I have a MimeType class which is a org.hibernate.usertype.UserType indeed.
import java.sql.Types;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MimeType extends EnumarationType{
private static final long serialVersionUID = 1L;
public static final MimeType XML = new MimeType(new Integer(0), "XML");
public static final MimeType JSON = new MimeType(new Integer(1), "JSON");
protected static ArrayList<MimeType> list = new ArrayList<MimeType>();
static {
SQL_TYPES = new int[] { Types.INTEGER };
list.add(XML);
list.add(JSON);
}
public MimeType(){
}
public MimeType(Integer value, String label) {
super(value, label);
}
public List<?> getList() {
return list;
}
public static MimeType getById(int id) {
Iterator<MimeType> it = list.iterator();
while (it.hasNext()) {
MimeType status = it.next();
int statusId = Integer.parseInt(status.getValue());
if (statusId == id)
return status;
}
return null;
}
public static MimeType getByName(String name) {
Iterator<MimeType> it = list.iterator();
while (it.hasNext()) {
MimeType status = it.next();
String statusName = status.getLabel();
if (statusName.equalsIgnoreCase(name))
return status;
}
return null;
}
}
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
public abstract class EnumarationTypeBase implements UserType, Serializable {
protected static int[] SQL_TYPES = { Types.VARCHAR };
protected String label;
protected Object value;
protected String resourceKey;
public EnumarationTypeBase() {
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public abstract List<?> getList();
private Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public EnumarationTypeBase resolveFromValue(Object value) {
List<?> list = getList();
if (list == null)
return null;
EnumarationTypeBase result = null;
for (Iterator<?> itr = list.iterator(); itr.hasNext();) {
EnumarationTypeBase enm = (EnumarationTypeBase) itr.next();
if (enm.getValue().toString().equals(value.toString())) {
result = enm;
break;
}
}
return result;
}
public EnumarationTypeBase resolveFromLabel(Object label) {
List<?> list = getList();
if (list == null)
return null;
EnumarationTypeBase result = null;
for (Iterator<?> itr = list.iterator(); itr.hasNext();) {
EnumarationTypeBase enm = (EnumarationTypeBase) itr.next();
if (enm.getLabel().equals(label.toString())) {
result = enm;
break;
}
}
return result;
}
public String toString() {
return getLabel();
}
public int[] sqlTypes() {
return SQL_TYPES;
}
public Class<?> returnedClass() {
return getClass();
}
public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException,
SQLException {
value = resultSet.getString(names[0]);
return resultSet.wasNull() ? null : resolveFromValue(value);
}
public void nullSafeSet(PreparedStatement statement, Object value, int index) throws HibernateException,
SQLException {
EnumarationTypeBase enumType = (EnumarationTypeBase) value;
if (value == null) {
statement.setNull(index, sqlTypes()[0]);
} else {
statement.setString(index, enumType.getValue().toString());
}
}
public boolean equals(Object x, Object y) {
if (x == y)
return true;
if (null == x || null == y)
return false;
return x.equals(y);
}
public boolean equals(Object obj) {
if (obj instanceof EnumarationTypeBase)
return this.getValue().equals(((EnumarationTypeBase) obj).getValue());
return super.equals(obj);
}
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
}
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
public Object deepCopy(Object value) {
return value;
}
public boolean isMutable() {
return false;
}
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
public int hashCode() {
return (new Integer(this.getValue().toString())).intValue();
}
public String getResourceKey() {
if (resourceKey == null)
resourceKey = resolveFromValue(this.value).resourceKey;
return resourceKey;
}
public void setResourceKey(String resourceKey) {
this.resourceKey = resourceKey;
}
}
public abstract class EnumarationType extends EnumarationTypeBase {
protected static int[] SQL_TYPES = { Types.VARCHAR };
public EnumarationType() {
}
public EnumarationType(Integer value, String label) {
this.value = value.toString();
this.label = label;
}
public EnumarationType(String value, String label) {
this.value = value.toString();
this.label = label;
}
public EnumarationType(Integer value, String label, String resourceKey) {
this.value = value.toString();
this.label = label;
this.resourceKey = resourceKey;
}
public String getValue() {
return (String) value;
}
public BigDecimal getBigDecimalValue() {
BigDecimal tValue = new BigDecimal(getValue());
return tValue;
}
public void setValue(String value) {
this.value = value;
}
}
So how could i define a manytomany relationship between the entity Platform and non-entity usertype MimeType.
Please help.
I solved the problem. Here is the working code
...
#ElementCollection(targetClass = MimeType.class,fetch=FetchType.EAGER)
#CollectionTable(name = "PLATFORM_MIME_TYPE", joinColumns = #JoinColumn(name = "PLATFORM_ID"))
#Enumerated(EnumType.ORDINAL)
#Column(name = "MIME_TYPE_ID", columnDefinition="integer")
#Type(
type = Constants.ENUMERATION_TYPE,
parameters = {
#Parameter(
name = "enumClass",
value = "com.ba.reme.model.enums.MimeType"),
#Parameter(
name = "identifierMethod",
value = "toInt"),
#Parameter(
name = "valueOfMethod",
value = "fromInt")
}
)
private Set<MimeType> supportedMimeTypes;
...
And the MimeType enum :
public enum MimeType {
XML(1),
JSON(2),
RSS(3);
private int value;
MimeType(int value) {
this.value = value;
}
// the identifierMethod
public int toInt() {
return value;
}
// the valueOfMethod
public static MimeType fromInt(int value) {
switch(value) {
case 2: return JSON;
case 3: return RSS;
default: return XML;
}
}
public String toString() {
switch(this) {
case RSS: return "rss";
case JSON: return "json";
default: return "xml";
}
}
}

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");
}