Java - Convert to correct json format using Jackson - java

I'm using Jackson to write a Java object to Json.
This is wath I am getting
{
"obj": [{
"Id": 1,
"type": "type1",
"properties": [{
"name": "PropN",
"value": "ValN"
}]
}, {
"id": 2,
"type": "type",
"properties": [{
"name": "Prop3",
"value": "Val3"
}]
}]
}
This is what i need to get:
{
"obj": [{
"id": 1,
"type": "type",
"properties": {
"name": "Eb1"
}
},
{
"id": 2,
"type": "type",
"properties": {
"name": "Eb2"
}
}
]
}
I dont know how to get the properties name and value "tags" from the json and also, remove the properties array to a list.
My Properties array is a simple POJO, and the Obj class has an ArrayList of properties.
Can someone tell me how to get this done?
Thanks.

You can use quicktype to generate the exact types you need. Here's what it produces with the JSON you require:
// Converter.java
// https://stackoverflow.com/questions/49055781/java-convert-to-correct-json-format-using-jackson
// import io.quicktype.Converter;
//
// Then you can deserialize a JSON string with
//
// StackOverflow data = Converter.fromJsonString(jsonString);
package io.quicktype;
import java.util.Map;
import java.io.IOException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.core.JsonProcessingException;
public class Converter {
// Serialize/deserialize helpers
public static StackOverflow fromJsonString(String json) throws IOException {
return getObjectReader().readValue(json);
}
public static String toJsonString(StackOverflow obj) throws JsonProcessingException {
return getObjectWriter().writeValueAsString(obj);
}
private static ObjectReader reader;
private static ObjectWriter writer;
private static void instantiateMapper() {
ObjectMapper mapper = new ObjectMapper();
reader = mapper.reader(StackOverflow.class);
writer = mapper.writerFor(StackOverflow.class);
}
private static ObjectReader getObjectReader() {
if (reader == null) instantiateMapper();
return reader;
}
private static ObjectWriter getObjectWriter() {
if (writer == null) instantiateMapper();
return writer;
}
}
// StackOverflow.java
package io.quicktype;
import java.util.Map;
import com.fasterxml.jackson.annotation.*;
public class StackOverflow {
private Obj[] obj;
#JsonProperty("obj")
public Obj[] getObj() { return obj; }
#JsonProperty("obj")
public void setObj(Obj[] value) { this.obj = value; }
}
// Obj.java
package io.quicktype;
import java.util.Map;
import com.fasterxml.jackson.annotation.*;
public class Obj {
private long id;
private String type;
private Properties properties;
#JsonProperty("id")
public long getID() { return id; }
#JsonProperty("id")
public void setID(long value) { this.id = value; }
#JsonProperty("type")
public String getType() { return type; }
#JsonProperty("type")
public void setType(String value) { this.type = value; }
#JsonProperty("properties")
public Properties getProperties() { return properties; }
#JsonProperty("properties")
public void setProperties(Properties value) { this.properties = value; }
}
// Properties.java
package io.quicktype;
import java.util.Map;
import com.fasterxml.jackson.annotation.*;
public class Properties {
private String name;
#JsonProperty("name")
public String getName() { return name; }
#JsonProperty("name")
public void setName(String value) { this.name = value; }
}

Related

How to get data from [Object] android

I am getting this response from my Express API Call.
Here's the Response:
{
"responseData": [{
"unitNames": [
"Matrices",
"Complex Numbers"
],
"subject": "maths",
"unitTopics": {
"1": [{
"topicName": "1.1 Introduction",
"topicURL": ""
},
{
"topicName": "1.2 Square Matrix",
"topicURL": ""
}
],
"2": [{
"topicName": "2.1 Numbers",
"topicURL": ""
}
]
}
}]
}
I got the response by using Retrofit in Android. It works great.But it can't parse Objects
Here's my Problem in Android Side.
{
"responseData": [{
"unitNames": [
"Matrices",
"Complex Numbers"
],
"subject": "maths",
"unitTopics": {
"1": [[Object],
[Object]
],
"2": [[Object]
]
}
}]
}
Its showing Object instead of my Data. How to fix this
Here's the Code:
System.out.println(response.body().getResponseData())
String received_data = response.body().getResponseData();
received_data_sub_units_topics_json = new JSONArray("["+received_data+"]");
System.out.println("MAIN2 "+received_data_sub_units_topics_json);
After converting to jsonarray, it shows like this,
{
"responseData": [{
"unitNames": [
"Matrices",
"Complex Numbers"
],
"subject": "maths",
"unitTopics": {
"1": [["Object"],
["Object"]
],
"2": [["Object"]
]
}
}]
}
Please help me with some solutions
For json i always use the library com.fasterxml.jackson.
You can use too org.json.JSONArray, org.json.JSONObject.
Here is an example of each one:
1- jackson
For implements this (is a bit long but you will convert it to java classes, so, you will can edit the values and obtain it more easily than if you use JSONObject), you have to create classes wich has the same structure than your json:
public class principalClass {
ArrayList<ResponseData> responseData;
...
//Getters, setters and constructors
}
public class ResponseData {
public ArrayList<String> unitNames;
public String subject;
public UnitTopics unitTopics;
...
//Getters, setters and constructors
}
public class UnitTopics {
public ArrayList<Topics> first;
public ArrayList<Topics> second;
...
//Getters, setters and constructors
}
public class Topics {
public String topicName;
public String topicURL;
...
//Getters, setters and constructors
}
Something like that, and then you use jackson to pass your json to you class principalClass:
ObjectMapper obj= new ObjectMapper();
PrincipalClass principal= obj.readValue(json, PrincipalClass.class);
The second posibility is to convert the values to JSONArray and JSONObject:
JSONObject bodyJSON = new JSONObject(json);
JSONArray responseData = bodyJSON.getJSONArray("responseData");
JSONArray unitNames= responseData.getJSONArray(0);
JSONObject subject= responseData.getJSONObject(1);
...
And if u want, u can loop through a JSONArray:
for (int i = 0; i < unitNames.length(); i++) {
String element = unitNames.getString(i);
}
You can use gson converter with retrofit to convert your json data to java object model class
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
Or you can convert json data to model class like
Gson gson = new Gson();
String jsonInString = "{your json data}";
ResponseModel response= gson.fromJson(jsonInString, ResponseModel.class);
Hey have you tried converting this JSON Object to a POJO.
I'd recommend using:
This website
It saves a lot of time and effort.
These will be your model classes:
package com.example.app;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ResponseDatum implements Serializable
{
#SerializedName("unitNames")
#Expose
private List<String> unitNames = null;
#SerializedName("subject")
#Expose
private String subject;
#SerializedName("unitTopics")
#Expose
private UnitTopics unitTopics;
public ResponseDatum() {
}
public ResponseDatum(List<String> unitNames, String subject, UnitTopics unitTopics) {
super();
this.unitNames = unitNames;
this.subject = subject;
this.unitTopics = unitTopics;
}
public List<String> getUnitNames() {
return unitNames;
}
public void setUnitNames(List<String> unitNames) {
this.unitNames = unitNames;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public UnitTopics getUnitTopics() {
return unitTopics;
}
public void setUnitTopics(UnitTopics unitTopics) {
this.unitTopics = unitTopics;
}
}
package com.example.app;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ResponseObject implements Serializable
{
#SerializedName("responseData")
#Expose
private List<ResponseDatum> responseData = null;
public ResponseObject() {
}
public ResponseObject(List<ResponseDatum> responseData) {
super();
this.responseData = responseData;
}
public List<ResponseDatum> getResponseData() {
return responseData;
}
public void setResponseData(List<ResponseDatum> responseData) {
this.responseData = responseData;
}
}
package com.example.app;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class UnitTopics implements Serializable
{
#SerializedName("1")
#Expose
private List<com.example.app._1> _1 = null;
#SerializedName("2")
#Expose
private List<com.example.app._2> _2 = null;
public UnitTopics() {
}
public UnitTopics(List<com.example.app._1> _1, List<com.example.app._2> _2) {
super();
this._1 = _1;
this._2 = _2;
}
public List<com.example.app._1> get1() {
return _1;
}
public void set1(List<com.example.app._1> _1) {
this._1 = _1;
}
public List<com.example.app._2> get2() {
return _2;
}
public void set2(List<com.example.app._2> _2) {
this._2 = _2;
}
}
package com.example.app;
import java.io.Serializable;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class _1 implements Serializable
{
#SerializedName("topicName")
#Expose
private String topicName;
#SerializedName("topicURL")
#Expose
private String topicURL;
public _1() {
}
public _1(String topicName, String topicURL) {
super();
this.topicName = topicName;
this.topicURL = topicURL;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getTopicURL() {
return topicURL;
}
public void setTopicURL(String topicURL) {
this.topicURL = topicURL;
}
}
package com.example.app;
import java.io.Serializable;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class _2 implements Serializable
{
#SerializedName("topicName")
#Expose
private String topicName;
#SerializedName("topicURL")
#Expose
private String topicURL;
public _2() {
}
public _2(String topicName, String topicURL) {
super();
this.topicName = topicName;
this.topicURL = topicURL;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getTopicURL() {
return topicURL;
}
public void setTopicURL(String topicURL) {
this.topicURL = topicURL;
}
}

Unable to deserialize HATEOS JSON using RestTemplate

I am trying to call a Spring Cloud Data Flow REST Endpoint which is supposed to return a list of all the executions of a task whose name is passed in the input.
For starters, I ran the following URL in the browser :
http://dataflow-server.myhost.net/tasks/executions?task1225
The following JSON is shown on the browser :
{
"_embedded": {
"taskExecutionResourceList": [
{
"executionId": 2908,
"exitCode": 0,
"taskName": "task1225",
"startTime": "2021-06-25T18:40:24.823+0000",
"endTime": "2021-06-25T18:40:27.585+0000",
"exitMessage": null,
"arguments": [
"--spring.datasource.username=******",
"--spring.cloud.task.name=task1225",
"--spring.datasource.url=******",
"--spring.datasource.driverClassName=org.h2.Driver",
"key=******",
"batchId=20210625_025755702",
"--spring.cloud.data.flow.platformname=default",
"--spring.cloud.task.executionid=2908"
],
"jobExecutionIds": [],
"errorMessage": null,
"externalExecutionId": "task1225-kp7mvwkmll",
"parentExecutionId": null,
"resourceUrl": "Docker Resource [docker:internal.artifactrepository.myhost.net/myProject/myimage:0.1]",
"appProperties": {
"spring.datasource.username": "******",
"spring.cloud.task.name": "task1225",
"spring.datasource.url": "******",
"spring.datasource.driverClassName": "org.h2.Driver"
},
"deploymentProperties": {
"spring.cloud.deployer.kubernetes.requests.memory": "512Mi",
"spring.cloud.deployer.kubernetes.limits.cpu": "1000m",
"spring.cloud.deployer.kubernetes.limits.memory": "8192Mi",
"spring.cloud.deployer.kubernetes.requests.cpu": "100m"
},
"taskExecutionStatus": "COMPLETE",
"_links": {
"self": {
"href": "http://dataflow-server.myhost.net/tasks/executions/2908"
}
}
}
]
},
"_links": {
"first": {
"href": "http://dataflow-server.myhost.net/tasks/executions?page=0&size=20"
},
"self": {
"href": "http://dataflow-server.myhost.net/tasks/executions?page=0&size=20"
},
"next": {
"href": "http://dataflow-server.myhost.net/tasks/executions?page=1&size=20"
},
"last": {
"href": "http://dataflow-server.myhost.net/tasks/executions?page=145&size=20"
}
},
"page": {
"size": 20,
"totalElements": 2908,
"totalPages": 146,
"number": 0
}
}
Next, I tried to call the same REST endpoint through Java; however, no matter what I try, the response object seems to be empty with none of the attributes populated :
Approach 1 : Custom domain classes created to deserialize the response. (Did not work. Empty content recieved in response)
ParameterizedTypeReference<Resources<TaskExecutions>> ptr = new ParameterizedTypeReference<Resources<TaskExecutions>>() {
};
ResponseEntity<Resources<TaskExecutions>> entity = restTemplate.exchange(
"http://dataflow-server.myhost.net/tasks/executions?task1225",
HttpMethod.GET, null, ptr);
System.out.println(entity.getBody().getContent()); **//empty content**
Where, TaskExecutions domain is as follows :
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({ "taskExecutionResourceList" })
#JsonIgnoreProperties(ignoreUnknown = true)
public class TaskExecutions {
public TaskExecutions() {
}
#JsonProperty("taskExecutionResourceList")
List<TaskExecutionResource> taskExecutionResourceList = new ArrayList<>();
#JsonProperty("taskExecutionResourceList")
public List<TaskExecutionResource> getTaskExecutionResourceList() {
return taskExecutionResourceList;
}
#JsonProperty("taskExecutionResourceList")
public void setTaskExecutionResourceList(List<TaskExecutionResource> taskExecutionResourceList) {
this.taskExecutionResourceList = taskExecutionResourceList;
}
}
And TaskExecutionResource is as follows :
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"executionId",
"exitCode",
"taskName",
"startTime",
"endTime",
"exitMessage",
"arguments",
"jobExecutionIds",
"errorMessage",
"externalExecutionId",
"parentExecutionId",
"resourceUrl",
"appProperties",
"deploymentProperties",
"taskExecutionStatus",
"_links" })
#JsonIgnoreProperties(ignoreUnknown = true)
public class TaskExecutionResource {
#JsonProperty("executionId")
private Integer executionId;
#JsonProperty("exitCode")
private Integer exitCode;
#JsonProperty("taskName")
private String taskName;
#JsonProperty("startTime")
private String startTime;
#JsonProperty("endTime")
private String endTime;
#JsonProperty("exitMessage")
private Object exitMessage;
#JsonProperty("arguments")
private List<String> arguments = new ArrayList<String>();
#JsonProperty("jobExecutionIds")
private List<Object> jobExecutionIds = new ArrayList<Object>();
#JsonProperty("errorMessage")
private Object errorMessage;
#JsonProperty("externalExecutionId")
private String externalExecutionId;
#JsonProperty("parentExecutionId")
private Object parentExecutionId;
#JsonProperty("resourceUrl")
private String resourceUrl;
#JsonProperty("appProperties")
private AppProperties appProperties;
#JsonProperty("deploymentProperties")
private DeploymentProperties deploymentProperties;
#JsonProperty("taskExecutionStatus")
private String taskExecutionStatus;
#JsonProperty("_links")
private Links links;
#JsonProperty("executionId")
public Integer getExecutionId() {
return executionId;
}
#JsonProperty("executionId")
public void setExecutionId(Integer executionId) {
this.executionId = executionId;
}
#JsonProperty("exitCode")
public Integer getExitCode() {
return exitCode;
}
#JsonProperty("exitCode")
public void setExitCode(Integer exitCode) {
this.exitCode = exitCode;
}
#JsonProperty("taskName")
public String getTaskName() {
return taskName;
}
#JsonProperty("taskName")
public void setTaskName(String taskName) {
this.taskName = taskName;
}
#JsonProperty("startTime")
public String getStartTime() {
return startTime;
}
#JsonProperty("startTime")
public void setStartTime(String startTime) {
this.startTime = startTime;
}
#JsonProperty("endTime")
public String getEndTime() {
return endTime;
}
#JsonProperty("endTime")
public void setEndTime(String endTime) {
this.endTime = endTime;
}
#JsonProperty("exitMessage")
public Object getExitMessage() {
return exitMessage;
}
#JsonProperty("exitMessage")
public void setExitMessage(Object exitMessage) {
this.exitMessage = exitMessage;
}
#JsonProperty("arguments")
public List<String> getArguments() {
return arguments;
}
#JsonProperty("arguments")
public void setArguments(List<String> arguments) {
this.arguments = arguments;
}
#JsonProperty("jobExecutionIds")
public List<Object> getJobExecutionIds() {
return jobExecutionIds;
}
#JsonProperty("jobExecutionIds")
public void setJobExecutionIds(List<Object> jobExecutionIds) {
this.jobExecutionIds = jobExecutionIds;
}
#JsonProperty("errorMessage")
public Object getErrorMessage() {
return errorMessage;
}
#JsonProperty("errorMessage")
public void setErrorMessage(Object errorMessage) {
this.errorMessage = errorMessage;
}
#JsonProperty("externalExecutionId")
public String getExternalExecutionId() {
return externalExecutionId;
}
#JsonProperty("externalExecutionId")
public void setExternalExecutionId(String externalExecutionId) {
this.externalExecutionId = externalExecutionId;
}
#JsonProperty("parentExecutionId")
public Object getParentExecutionId() {
return parentExecutionId;
}
#JsonProperty("parentExecutionId")
public void setParentExecutionId(Object parentExecutionId) {
this.parentExecutionId = parentExecutionId;
}
#JsonProperty("resourceUrl")
public String getResourceUrl() {
return resourceUrl;
}
#JsonProperty("resourceUrl")
public void setResourceUrl(String resourceUrl) {
this.resourceUrl = resourceUrl;
}
#JsonProperty("appProperties")
public AppProperties getAppProperties() {
return appProperties;
}
#JsonProperty("appProperties")
public void setAppProperties(AppProperties appProperties) {
this.appProperties = appProperties;
}
#JsonProperty("deploymentProperties")
public DeploymentProperties getDeploymentProperties() {
return deploymentProperties;
}
#JsonProperty("deploymentProperties")
public void setDeploymentProperties(DeploymentProperties deploymentProperties) {
this.deploymentProperties = deploymentProperties;
}
#JsonProperty("taskExecutionStatus")
public String getTaskExecutionStatus() {
return taskExecutionStatus;
}
#JsonProperty("taskExecutionStatus")
public void setTaskExecutionStatus(String taskExecutionStatus) {
this.taskExecutionStatus = taskExecutionStatus;
}
#JsonProperty("_links")
public Links getLinks() {
return links;
}
#JsonProperty("_links")
public void setLinks(Links links) {
this.links = links;
}
}
Approach 2 : Add spring-cloud-data-flow-rest as a maven dependency in my project and use the TaskExectuionResource entity defined in this project. :
TaskExecutionResource.Page = restTemplate.getForObject("http://dataflow-server.myhost.net/tasks/executions?task1225",
TaskExecutionResource.Page.class);//**Empty content**
Question : How can I deserialize the response of the JSON returned by a rest enndpoint that is using HATEOAS? It seems like a very daunting task to get this to work.
Not sure how you constructed RestTemplate but it doesn't work as is with hateoas and there's some additional steps you need to do.
To get idea what we've done see ObjectMapper config. There's hal module and additional mixin's what mapper needs to be aware of for these things to work.

I need to test my entity classes using a parse tool to ensure that everything is working

I have given a json format which is like below and I am asked to convert this json format to entity classes.
{
"descriptor": {
"reportName": "Shop Drawing Progress Report",
"subLabel": "My Workflow Project",
"columnGroups": [
{
"groupName": "mainData",
"groupLabel": "",
"frozen": true,
"columns": [
{
"field": "identifier",
"label": "Workflow Prefix",
"sortable": true,
"editable": false,
"dataType": "String"
}
]
}]
I create entity classes from above json string and one of those entity class sample is below
public class TabularColumn {
private String field;
private String label;
private boolean sortable;
private boolean editable;
private String dataType;
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public boolean isSortable() {
return sortable;
}
public void setSortable(boolean sortable) {
this.sortable = sortable;
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
I have to test using parseDesciptor tool which is there in my application to make sure my entity classes generated from the json format are correct.How can I do that?
Here is my parseDecriptor tool which I am using in my java application
public <T> T parseDescriptor(String json, Class<T> c) throws IOException {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.getDeserializationConfig().disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.getDeserializationConfig().enable(DeserializationConfig.Feature.USE_ANNOTATIONS);
T ret = mapper.readValue(json, c);
if (!(ret instanceof ReportDescriptor)) {
throw new IllegalArgumentException("The specified class of type "+c.getCanonicalName()+" does not extend ReportDescriptor");
}
return ret;
}

JSON to Java Object get property to compare

After using http://www.jsonschema2pojo.org/ to create POJO class to convert JSON to Java Object I'm trying to get property of "distance" "inMeters" to compare them but I can't get them because it is List is there any way I can compare them
{
"originAddresses": [
"58 Oxford St, Fitzrovia, London W1D 1BH, UK"
],
"destinationAddresses": [
"109 Marylebone High St, Marylebone, London W1U 4RX, UK",
"143 Great Titchfield St, Fitzrovia, London W1W, UK",
"210 Great Portland St, Fitzrovia, London W1W 5BQ, UK",
"43-51 Great Titchfield St, Fitzrovia, London W1W 7PQ, UK"
],
"rows": [
{
"elements": [
{
"status": "OK",
"duration": {
"inSeconds": 457,
"humanReadable": "8 mins"
},
"distance": {
"inMeters": 1662,
"humanReadable": "1.7 km"
}
},
{
"status": "OK",
"duration": {
"inSeconds": 383,
"humanReadable": "6 mins"
},
"distance": {
"inMeters": 1299,
"humanReadable": "1.3 km"
}
},
{
"status": "OK",
"duration": {
"inSeconds": 376,
"humanReadable": "6 mins"
},
"distance": {
"inMeters": 1352,
"humanReadable": "1.4 km"
}
},
{
"status": "OK",
"duration": {
"inSeconds": 366,
"humanReadable": "6 mins"
},
"distance": {
"inMeters": 932,
"humanReadable": "0.9 km"
}
}
]
}
]
}
This is my Main POJO Class in the compareTo class it require int but it show only List :
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class LocationGoogle implements Comparable<LocationGoogle> {
public LocationGoogle(String originAddress, String destinationAddress,Row
rows){
super();
this.destinationAddresses = destinationAddresses;
this.originAddresses = originAddresses;
this.rows= (List<Row>) rows;
}
#SerializedName("originAddresses")
#Expose
private List<String> originAddresses = null;
#SerializedName("destinationAddresses")
#Expose
private List<String> destinationAddresses = null;
#SerializedName("rows")
#Expose
private List<Row> rows = null;
public List<String> getOriginAddresses(){
return originAddresses;
}
public void setOriginAddresses(List<String> originAddresses){
this.originAddresses = originAddresses;
}
public List<String> getDestinationAddresses(){
return destinationAddresses;
}
public void setDestinationAddresses(List<String> destinationAddresses){
this.destinationAddresses = destinationAddresses;
}
public List<Row> getRows(){
return rows;
}
public void setRows(List<Row> rows){
this.rows = rows;
}
#Override
public int compareTo(LocationGoogle compareTime){
int compare =((LocationGoogle)compareTime).getRows();
return 0;
}
}
Is JSON to Java Object is good or bad way to convert JSON to java data. Should I keep doing this or find another way?
This is class Row :
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Row {
#SerializedName("elements")
#Expose
private List<Element> elements = null;
public List<Element> getElements() {
return elements;
}
public void setElements(List<Element> elements) {
this.elements = elements;
}
#Override
public String toString(){
return String.valueOf(elements);
}
}
This is Elements class:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Element {
#SerializedName("status")
#Expose
private String status;
#SerializedName("duration")
#Expose
private Duration duration;
#SerializedName("distance")
#Expose
private Distance distance;
#Override
public String toString(){
return String.valueOf(distance);
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public Distance getDistance() {
return distance;
}
public void setDistance(Distance distance) {
this.distance = distance;
}
}
This is Duration class:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Duration {
#SerializedName("inSeconds")
#Expose
private Integer inSeconds;
#SerializedName("humanReadable")
#Expose
private String humanReadable;
public Integer getInSeconds() {
return inSeconds;
}
public void setInSeconds(Integer inSeconds) {
this.inSeconds = inSeconds;
}
public String getHumanReadable() {
return humanReadable;
}
public void setHumanReadable(String humanReadable) {
this.humanReadable = humanReadable;
}
#Override
public String toString (){
return String.valueOf(inSeconds);
}
}
This is Distance class:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Distance implements Comparable{
#SerializedName("inMeters")
#Expose
private Integer inMeters;
#SerializedName("humanReadable")
#Expose
private String humanReadable;
public Integer getInMeters() {
return inMeters;
}
public void setInMeters(Integer inMeters) {
this.inMeters = inMeters;
}
public String getHumanReadable() {
return humanReadable;
}
public void setHumanReadable(String humanReadable) {
this.humanReadable = humanReadable;
}
#Override
public String toString(){
return String.valueOf(inMeters);
}
#Override
public int compareTo(Object o){
int compare = ((Distance)o).getInMeters();
return compare-this.inMeters;
}
}
The code i using to compare them:
#Override
public int compareTo(LocationGoogle compareTime){
String i= getRows()
int compare =((LocationGoogle)compareTime).getRows();
return 0;
}
After seeing required int but have List i confusing.
FileReader reader = new FileReader("Path to json file");
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(reader);
System.out.println("json object = "+json.toString());
JSONArray result = (JSONArray) json.get("rows");
JSONObject result1 = (JSONObject)result.get(0);
JSONArray elements = (JSONArray) result1.get("elements");
JSONObject result2 = (JSONObject)elements.get(0);
JSONObject distance = (JSONObject)result2.get("distance");
JSONObject duration = (JSONObject)result2.get("duration");
Distance=(String)distance.get("inMeters");
use json_simple-1.0.2.jar file. It is step by step extraction.

Parsing and storing a json response in android

My JSON response has the following structure.
How should i parse it to store in a list in java with the structure maintained.
Does GSON provide a solution or should i use multidimensional array list?
I need to pass each of the tag array to a different view pager what approach should I follow.
{
"tag": [
{
"listing_count": 5,
"listings": [
{
"source": "source1",
"data": {
"image": "image1",
"name": "name1"
},
"name": "name1"
}
]
},
{
"listing_count": 5,
"listings": [
{
"source": "source2",
"data": {
"image": "imag2",
"name": "name2"
},
"name": "name2"
}
]
}
]
}
EDIT:
I have created the classes as suggested in the answer..I am having trouble creating the GSON response class.
This is what I have created:
public GsonRequest(int method, String url, Class<T> clazz,
Listener<T> listener, ErrorListener errorListener, Gson gson) {
super(Method.GET, url, errorListener);
this.mClazz = clazz;
this.mListener = listener;
mGson = gson;
}
The gson class should be something like this:
public class TagList {
ArrayList<Tag> tags;
public static class Tag {
int listing_count;
ArrayList<Listings> listings;
public int getListing_count() {
return listing_count;
}
public void setListing_count(int listing_count) {
this.listing_count = listing_count;
}
public ArrayList<Listings> getListings() {
return listings;
}
public void setListings(ArrayList<Listings> listings) {
this.listings = listings;
}
}
public static class Listings {
String source;
Data data;
String name;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class Data {
String image;
String name;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Categories