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");
}
Related
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
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);
}
My json request is as follows
{
"division":"XX",
"category":"XX",
"operation":"XXX",
"transactionId":"XX",
"trackNumber":"XXx",
"attentionReason":"",
"carNeedAttention":"",
"chargableDamage":"X",
"missingItems":"",
"offences":"N",
"outInAgentNumber":"XX",
"cList":{
{
"id":"230",
"elementCode":"XXX",
"value":"XXX",
"comment":"XX",
"label":"",
"uiComponent":"",
"featureType":""
}
},
"outInCprNumber":"XX",
"outInDate":"",
"outInDuration":"",
"outInFuel":"75",
"outInKm":"9999",
"outInRem1":"",
"outInRem2":"",
"outInRem3":"",
"userName":"XX",
"vehicleRetBy":""
}
I have a spring rest controller class
#Controller
#RequestMapping("/services")
public class CheckListController {
#RequestMapping(value = "/checkList", method = RequestMethod.POST, consumes="application/json",produces="application/json")
public ModelMap updateCheckList(#RequestBody CheckList checkList){
ModelMap modelMap = new ModelMap();
return modelMap;
}
}
CheckList class is as follows
import java.util.List;
public class CheckList {
String division;
String category;
String operation;
String transactionId;
String trackNumber;
String attentionReason;
String carNeedAttention;
String chargableDamage;
String missingItems;
String offences;
String outInAgentNumber;
List<MetaData> cList;
String outInCprNumber;
String outInDate;
String outInDuration;
String outInFuel;
String outInKm;
String outInRem1;
String outInRem2;
String outInRem3;
String userName;
String vehicleRetBy;
String updateMasterImage;
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getTrackNumber() {
return trackNumber;
}
public void setTrackNumber(String trackNumber) {
this.trackNumber = trackNumber;
}
public String getAttentionReason() {
return attentionReason;
}
public void setAttentionReason(String attentionReason) {
this.attentionReason = attentionReason;
}
public String getCarNeedAttention() {
return carNeedAttention;
}
public void setCarNeedAttention(String carNeedAttention) {
this.carNeedAttention = carNeedAttention;
}
public String getChargableDamage() {
return chargableDamage;
}
public void setChargableDamage(String chargableDamage) {
this.chargableDamage = chargableDamage;
}
public String getMissingItems() {
return missingItems;
}
public void setMissingItems(String missingItems) {
this.missingItems = missingItems;
}
public String getOffences() {
return offences;
}
public void setOffences(String offences) {
this.offences = offences;
}
public List<MetaData> getcList() {
return cList;
}
public void setcList(List<MetaData> cList) {
this.cList = cList;
}
// public AccessoryList getAccessoryList() {
// return accessoryList;
// }
//
// public void setAccessoryList(AccessoryList accessoryList) {
// this.accessoryList = accessoryList;
// }
public String getOutInCprNumber() {
return outInCprNumber;
}
public void setOutInCprNumber(String outInCprNumber) {
this.outInCprNumber = outInCprNumber;
}
public String getOutInDate() {
return outInDate;
}
public void setOutInDate(String outInDate) {
this.outInDate = outInDate;
}
public String getOutInRem1() {
return outInRem1;
}
public void setOutInRem1(String outInRem1) {
this.outInRem1 = outInRem1;
}
public String getOutInRem2() {
return outInRem2;
}
public void setOutInRem2(String outInRem2) {
this.outInRem2 = outInRem2;
}
public String getOutInRem3() {
return outInRem3;
}
public void setOutInRem3(String outInRem3) {
this.outInRem3 = outInRem3;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getVehicleRetBy() {
return vehicleRetBy;
}
public void setVehicleRetBy(String vehicleRetBy) {
this.vehicleRetBy = vehicleRetBy;
}
public String getUpdateMasterImage() {
return updateMasterImage;
}
public void setUpdateMasterImage(String updateMasterImage) {
this.updateMasterImage = updateMasterImage;
}
public String getOutInAgentNumber() {
return outInAgentNumber;
}
public void setOutInAgentNumber(String outInAgentNumber) {
this.outInAgentNumber = outInAgentNumber;
}
public String getOutInDuration() {
return outInDuration;
}
public void setOutInDuration(String outInDuration) {
this.outInDuration = outInDuration;
}
public String getOutInFuel() {
return outInFuel;
}
public void setOutInFuel(String outInFuel) {
this.outInFuel = outInFuel;
}
public String getOutInKm() {
return outInKm;
}
public void setOutInKm(String outInKm) {
this.outInKm = outInKm;
}
}
MetaData is as folows
public class MetaData{
Integer id;
String label;
String uiComponent;
String featureType;
String value;
String comment;
String elementCode;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setId(int id)
{
this.id = id;
}
public String getLabel()
{
return label;
}
public void setLabel(String label)
{
this.label = label;
}
public String getUiComponent()
{
return uiComponent;
}
public void setUiComponent(String uiComponent)
{
this.uiComponent = uiComponent;
}
public String getFeatureType()
{
return featureType;
}
public void setFeatureType(String featureType)
{
this.featureType = featureType;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getElementCode() {
return elementCode;
}
public void setElementCode(String elementCode) {
this.elementCode = elementCode;
}
}
But when i submitting the json request it is giving 415 unsuporrted media type error.
What is wrong with this code. Do anybody havve the answer. Thanks in advance.
Nothing with the code. You just need to make sure that Your POST request has the HTTP Content-Type header set to "application/json".
If you use curl to POST the data you can use the following parameter to set the header value:
curl -H "Content-Type:application/json"
Add an Accept header too:
curl -H "Content-Type:application/json" -H "Accept:application/json"
I'm seeing weird inexplicable errors using Spring restTemplate and I think it might be related to an incorrect object map (I'm just learning). Here is the json from the head to the fields being mapped:
{
"response": {
"version":"0.1",
"termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"conditions": 1
}
}
, "current_observation": {
"image": {
"url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",
"title":"Weather Underground",
"link":"http://www.wunderground.com"
},
"display_location": {
"full":"San Francisco, CA",
"city":"San Francisco",
"state":"CA",
"state_name":"California",
"country":"US",
"country_iso3166":"US",
"zip":"94101",
"magic":"1",
"wmo":"99999",
"latitude":"37.77500916",
"longitude":"-122.41825867",
"elevation":"47.00000000"
},
And here is my map:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Display {
private String full;
private String city;
private String state;
private String state_name;
private String country;
private String country_iso3166;
private String zip;
private String magic;
private String who;
private String lattitude;
private String logitude;
private String elevation;
public String getFull() {
return full;
}
public void setFull(String full) {
this.full = full;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getState_name() {
return state_name;
}
public void setState_name(String state_name) {
this.state_name = state_name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountry_iso3166() {
return country_iso3166;
}
public void setCountry_iso3166(String country_iso3166) {
this.country_iso3166 = country_iso3166;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getMagic() {
return magic;
}
public void setMagic(String magic) {
this.magic = magic;
}
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
public String getLattitude() {
return lattitude;
}
public void setLattitude(String lattitude) {
this.lattitude = lattitude;
}
public String getLogitude() {
return logitude;
}
public void setLogitude(String logitude) {
this.logitude = logitude;
}
public String getElevation() {
return elevation;
}
public void setElevation(String elevation) {
this.elevation = elevation;
}
}
Is there a problem with the way I've written the map?
Thanks,
Rob
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);