How do I parse this JSON response into POJO - java

I have the following Test class:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ibm.cio.cloud.cost.model.ElasticResponse;
import com.jayway.jsonpath.JsonPath;
#JsonIgnoreProperties(ignoreUnknown = true)
public class TestJSONPaths {
private static final String json = "{\"hits\":{\"total\":1,\"hits\":[{\"_id\":\"oEE4j2QBXCNPxFWHqq3i\",\"_score\":1.0,\"_source\":{\"status\":\"SUCCESSFUL\",\"reason\":\"OK, Single ACTIVE status can process\"}}]}}";
public static void main(String[] args) {
List<String> strippedJSON = JsonPath.read(json, "$.hits.hits._source");
ElasticResponse response = null;
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
try {
System.out.println("From this json string:" + strippedJSON + "\n");
response = mapper.readValue(strippedJSON.toString(), ElasticResponse.class);
System.out.println("ElasticDocument=" + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getDocuments()));
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is the ElasticResponse class def:
public class ElasticResponse {
private List<ElasticDocument> documents;
public List<ElasticDocument> getDocuments() {
return documents;
}
public void setDocuments(List<ElasticDocument> documents) {
this.documents = documents;
}
}
public class ElasticDocument {
private String _id;
private String status;
private String reason;
... getters/setters
}
I'm trying to get a ElasticDocument object mapped from the JSON given but it's throwing the following errors below. I'm attempting to filtered out the JSON to simply be: [{_source document values }]. This error occurs on the very first line in the Main class. How can I map this Json?
[DEBUG] Evaluating path: $['hits']['hits']['_source']
Exception in thread "main" com.jayway.jsonpath.PathNotFoundException: Expected to find an object with property ['_source'] in path $['hits']['hits'] but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
at com.jayway.jsonpath.internal.path.PropertyPathToken.evaluate(PropertyPathToken.java:71)
at com.jayway.jsonpath.internal.path.PathToken.handleObjectProperty(PathToken.java:81)
at com.jayway.jsonpath.internal.path.PropertyPathToken.evaluate(PropertyPathToken.java:79)
at com.jayway.jsonpath.internal.path.PathToken.handleObjectProperty(PathToken.java:81)
at com.jayway.jsonpath.internal.path.PropertyPathToken.evaluate(PropertyPathToken.java:79)
at com.jayway.jsonpath.internal.path.RootPathToken.evaluate(RootPathToken.java:62)
at com.jayway.jsonpath.internal.path.CompiledPath.evaluate(CompiledPath.java:53)
at com.jayway.jsonpath.internal.path.CompiledPath.evaluate(CompiledPath.java:61)
at com.jayway.jsonpath.JsonPath.read(JsonPath.java:187)
at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:102)
at com.jayway.jsonpath.internal.JsonContext.read(JsonContext.java:89)
at com.jayway.jsonpath.JsonPath.read(JsonPath.java:502)
at com.ibm.cio.cloud.cost.TestJSONPaths.main(TestJSONPaths.java:18)

The exception is due to the jsonpath returning an array instead of an object, so if you fix the jsonpath to look like this:
$.hits.hits[*]._source
Then it will evaluate properly. However, this probably still doesn't do what you want it to do.. The JsonPath.read() will deserialise the JSON for you. But you have to watch out with this:
public class Test {
private static final String json = "{\"hits\":{\"total\":1,\"hits\":[{\"_id\":\"oEE4j2QBXCNPxFWHqq3i\",\"_score\":1.0,\"_source\":{\"status\":\"SUCCESSFUL\",\"reason\":\"OK, Single ACTIVE status can process\"}}]}}";
public static void main(String[] args) {
List<ElasticDocument> docs = JsonPath.read(json, "$.hits.hits[*]._source");
System.out.println("elasticDoc: " + docs.get(0));
}
public static class ElasticDocument {
public String _id;
public String status;
public String reason;
#Override
public String toString() {
return "ElasticDocument{" +
"_id='" + _id + '\'' +
", status='" + status + '\'' +
", reason='" + reason + '\'' +
'}';
}
}
}
Looks like it works, however the docs List is now actually a List of Maps. Apparently It's possible to register JsonPath with Jackson but I can't make it work
Alternatively you can use Jackson to deserialise the JSON, then you should create an object model that matches the json structure and then you can use the ObjectMapper to do the deserialisation
public class Test {
private static final String json = "{\"hits\":{\"total\":1,\"hits\":[{\"_id\":\"oEE4j2QBXCNPxFWHqq3i\",\"_score\":1.0,\"_source\":{\"status\":\"SUCCESSFUL\",\"reason\":\"OK, Single ACTIVE status can process\"}}]}}";
public static void main(String[] args) {
System.out.println("From this json string:" + json + "\n");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
try {
HitsResource hitsResource = mapper.readValue(json, HitsResource.class);
System.out.println("jackson elasticDoc: " + hitsResource.hitsParent.hits.get(0).source);
} catch (Exception e) {
e.printStackTrace();
}
}
public static class HitsResource {
#JsonProperty("hits")
public HitsParent hitsParent;
#Override
public String toString() {
return "HitsResource{" +
"hitsParent=" + hitsParent +
'}';
}
}
public static class HitsParent {
#JsonProperty("total")
public Long total;
#JsonProperty("hits")
public List<Hits> hits;
#Override
public String toString() {
return "HitsParent{" +
"total=" + total +
", hits=" + hits +
'}';
}
}
public static class Hits {
#JsonProperty("_id")
public String id;
#JsonProperty("_score")
public BigDecimal score;
#JsonProperty("_source")
public ElasticDocument source;
#Override
public String toString() {
return "Hits{" +
"id='" + id + '\'' +
", score=" + score +
", source=" + source +
'}';
}
}
public static class ElasticDocument {
#JsonProperty("_id")
public String _id;
#JsonProperty("status")
public String status;
#JsonProperty("reason")
public String reason;
#Override
public String toString() {
return "ElasticDocument{" +
"_id='" + _id + '\'' +
", status='" + status + '\'' +
", reason='" + reason + '\'' +
'}';
}
}
}

Related

How do I get an array value instead of reference from ObjectMapper in Jackson?

I am trying to get a result from an API response and am able to map everything except for columnHeaders, which is an array of ColumnHeaders. I am instead getting a reference to an array. The code is below.
Response Class
public class Response {
#JsonProperty("searchApiFormatVersion")
private String searchApiFormatVersion;
#JsonProperty("searchName")
private String searchName;
#JsonProperty("description")
private String description;
#JsonProperty("columnHeaders")
private ColumnHeader[] columnHeaders;
public Response(String searchApiFormatVersion, String searchName, String description,
ColumnHeader[] columnHeaders) {
this.searchApiFormatVersion = searchApiFormatVersion;
this.searchName = searchName;
this.description = description;
this.columnHeaders = columnHeaders;
}
public Response(){
}
public String getSearchApiFormatVersion() {
return searchApiFormatVersion;
}
public void setSearchApiFormatVersion(String searchApiFormatVersion) {
this.searchApiFormatVersion = searchApiFormatVersion;
}
public String getSearchName() {
return searchName;
}
public void setSearchName(String searchName) {
this.searchName = searchName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ColumnHeader[] getColumnHeaders() {
return columnHeaders;
}
public void setColumnHeaders(ColumnHeader[] columnHeaders) {
this.columnHeaders = columnHeaders;
}
#Override
public String toString() {
return "Response{" +
"searchApiFormatVersion='" + searchApiFormatVersion + '\'' +
", searchName='" + searchName + '\'' +
", description='" + description + '\'' +
", totalRowCount=" + totalRowCount +
", returnedRowCount=" + returnedRowCount +
", startingReturnedRowNumber=" + startingReturnedRowNumber +
", basetype='" + basetype + '\'' +
", columnCount=" + columnCount +
", columnHeaders=" + columnHeaders +
'}';
}
}
ColumnHeader class
public class ColumnHeader {
#JsonProperty("text")
private String text;
#JsonProperty("dataType")
private String dataType;
#JsonProperty("hierarchy")
private int hierarchy;
#JsonProperty("parentName")
private String parentName;
#JsonProperty("isEntity")
private Boolean isEntity;
#JsonProperty("isEset")
private Boolean isEset;
public ColumnHeader(String text, String dataType, int hierarchy, String parentName, Boolean isEntity, Boolean isEset) {
this.text = text;
this.dataType = dataType;
this.hierarchy = hierarchy;
this.parentName = parentName;
this.isEntity = isEntity;
this.isEset = isEset;
}
public ColumnHeader(){
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public int getHierarchy() {
return hierarchy;
}
public void setHierarchy(int hierarchy) {
this.hierarchy = hierarchy;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public Boolean getEntity() {
return isEntity;
}
public void setEntity(Boolean entity) {
isEntity = entity;
}
public Boolean getEset() {
return isEset;
}
public void setEset(Boolean eset) {
isEset = eset;
}
#Override
public String toString() {
return "ColumnHeader{" +
"text='" + text + '\'' +
", dataType='" + dataType + '\'' +
", hierarchy=" + hierarchy +
", parentName='" + parentName + '\'' +
", isEntity=" + isEntity +
", isEset=" + isEset +
'}';
}
}
Service Class
public class BudgetEffortResponseService {
Logger logger = LoggerFactory.getLogger(Response.class);
public Response getResponseFromStringJsonApiResponse(String stringJsonResponse) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper(); //Used to map objects from JSON values specified in Award under #JsonProperty annotation
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JSONObject stringJsonResponseTurnedIntoJsonObject = new JSONObject(stringJsonResponse);
logger.info("stringJsonResponseTurnedIntoJsonObject: " + stringJsonResponseTurnedIntoJsonObject);
return objectMapper.readValue(stringJsonResponseTurnedIntoJsonObject.toString(), Response.class);
}
}
Main Class
#SpringBootApplication
public class EtlApplication {
public static final String API_USERNAME = System.getenv("API_USERNAME");
public static final String API_PASSWORD = System.getenv("API_PASSWORD");
public static final String API_PREFIX = System.getenv("API_PREFIX");
public static final String API_PATH = System.getenv("API_PATH");
public static void main(String[] args) throws URISyntaxException, JsonProcessingException {
Logger logger = LoggerFactory.getLogger(EtlApplication.class);
logger.info("--------------------Starting process--------------------");
AwardRepository awardRepository = new AwardRepository();
AwardService awardService = new AwardService();
ApiResponseRowService apiResponseRowService = new ApiResponseRowService();
ApiResponseRepository apiResponseRepository = new ApiResponseRepository();
BudgetEffortResponseService budgetEffortResponseService = new BudgetEffortResponseService();
Date startDateForApiPull = new GregorianCalendar(2023, Calendar.FEBRUARY, 1).getTime();
Date endDateForApiPull = new GregorianCalendar(2023, Calendar.FEBRUARY, 2).getTime();
logger.info("============Starting BudgetEffort API pull from Huron===============");
HttpResponse<String> budgetEffortHttpResponse = apiResponseRepository.getHttpResponseFromApi(startDateForApiPull,
endDateForApiPull, 1, -1, API_PREFIX, API_PATH,
API_USERNAME, API_PASSWORD);
logger.info("BudgetEffortHttpResponse: " + budgetEffortHttpResponse);
logger.info("============End of BudgetEffort API pull from Huron===============");
//Get body of http response string
String budgetEffortResponseString = budgetEffortHttpResponse.body();
logger.info("BudgetEffortResponseString: " + budgetEffortResponseString);
Response budgetEffortResponse = budgetEffortResponseService.getResponseFromStringJsonApiResponse(budgetEffortResponseString);
logger.info("BudgetEffortResponse: " + budgetEffortResponse);
logger.info("--------------------End of process--------------------");
}
}
The response. I'm noticing that I'm getting the reference to the array for columnHeaders and not the values. How would I get the values? Thank you.
BudgetEffortResponse: Response{searchApiFormatVersion='1.0', searchName='Personnel Details for Authorized allocations on Active Awards', description='', columnHeaders=[Lcom.example.etl.entity.budgetEffort.ColumnHeader;#7a7471ce}
The response you get is ok. And also the Array is good. The line
logger.info("BudgetEffortResponse: " + budgetEffortResponse);
uses an indirect cast to String of the Object budgetEffortResponse. In this case all toString() methods of the objects are called. What you need to do in order to print out the Objects is to implement/add the toString() method in the class com.example.etl.entity.budgetEffort.ColumnHeader
Update:
As the toString method is already implemented, the above is partially wrong. But there is a way to use a setting of the ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
// pretty print
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(budgetEffortResponse);
logger.info("BudgetEffortResponse: " + json);

Java Android FCM parse data to object

I want to parse json which I send to my phone. this is what I get :
In params I get two string
UPDATE_ROUTE
and
[{"card_id":"3a296050-b7dc-4f7b-a041-162817090520","t_tasks_e_dic_load_types_sj_id":132,"status_id":2,"eup":"86baeff7e","card_nr":"211","change_time":"2019-12-17T12:04:43.129Z"}]
this is my class :
public class FCMResponse{
#SerializedName("data")
private List<DataItem> data;
#SerializedName("type")
private String type;
}
I try do this :
FCMResponse fcm = g.fromJson("\"data\":"+updateResponse.getData(), FCMResponse.class);
but when I try parse this or try parse string to my java class I get :
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $
According to this response,
[{"card_id":"3a296050-b7dc-4f7b-a041-162817090520","t_tasks_e_dic_load_types_sj_id":132,"status_id":2,"eup":"86baeff7e","card_nr":"211","change_time":"2019-12-17T12:04:43.129Z"}]
your model class should be
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("card_id")
#Expose
private String cardId;
#SerializedName("t_tasks_e_dic_load_types_sj_id")
#Expose
private Integer tTasksEDicLoadTypesSjId;
#SerializedName("status_id")
#Expose
private Integer statusId;
#SerializedName("eup")
#Expose
private String eup;
#SerializedName("card_nr")
#Expose
private String cardNr;
#SerializedName("change_time")
#Expose
private String changeTime;
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public Integer getTTasksEDicLoadTypesSjId() {
return tTasksEDicLoadTypesSjId;
}
public void setTTasksEDicLoadTypesSjId(Integer tTasksEDicLoadTypesSjId) {
this.tTasksEDicLoadTypesSjId = tTasksEDicLoadTypesSjId;
}
public Integer getStatusId() {
return statusId;
}
public void setStatusId(Integer statusId) {
this.statusId = statusId;
}
public String getEup() {
return eup;
}
public void setEup(String eup) {
this.eup = eup;
}
public String getCardNr() {
return cardNr;
}
public void setCardNr(String cardNr) {
this.cardNr = cardNr;
}
public String getChangeTime() {
return changeTime;
}
public void setChangeTime(String changeTime) {
this.changeTime = changeTime;
}
#Override
public String toString() {
return "Example{" +
"cardId='" + cardId + '\'' +
", tTasksEDicLoadTypesSjId=" + tTasksEDicLoadTypesSjId +
", statusId=" + statusId +
", eup='" + eup + '\'' +
", cardNr='" + cardNr + '\'' +
", changeTime='" + changeTime + '\'' +
'}';
}
}
And you can fetch in class like,
Gson gson = new Gson();
Example[] examples = gson.fromJson(response, Example[].class);
Example example = examples[0];

Spring boot websocket send jsonstring

I'm new to spring boot, and I'm trying to send back jsonstring using websocket but I don't think it is returning correct jsonstring format.
RMModel.java
public class RMModel {
private Integer inQueue;
private Integer suspended;
public RMModel getMessage() {
this.inQueue = new Random().nextInt(11);
this.suspended = new Random().nextInt(11);
return this;
}
#Override
public String toString() {
return "{" + "\"inqueue\":" + this.inQueue + "," + "\"suspended\":" + this.suspended + '}';
}
}
WebSocketScheduler.java
#Component
public class WebSocketScheduler {
#Autowired
private SimpMessagingTemplate template;
#Scheduled(fixedRate = 1000)
public void publishData() {
String data = RMModel.getData().toString();
this.template.convertAndSend("/topic/recon", data);
}
}
So I want to return RMModel's jsonstring to the client. I have angular2 client
this._stompService.subscribe('/topic/recon').subscribe(res => console.log(JSON.parse(res.body)));
It is not converting to json object.
What is the correct way to return jsonstring in spring boot?
problem solved.
The model shouldn't have a method that returns itself, jackson will throw an exception.
RMModel.java
public class RMModel {
private Integer inQueue;
private Integer suspended;
public Integer getInQueue() {
return inQueue;
}
public void setInQueue(Integer maximum) {
this.inQueue = new Random().nextInt(maximum);
}
public Integer getSuspended() {
return suspended;
}
public void setSuspended(Integer maximum) {
this.suspended = new Random().nextInt(maximum);
}
#Override
public String toString() {
return "{" + "\"inqueue\":" + this.inQueue + "," + "\"suspended\":" + this.suspended + '}';
}

How to convert JSON object from third party api into local POJO

Let's say i make a call to a thrid party API to get a object Task and I get the following JSON String in return:
{
"tasks": [
{
"id": 1,
"code": "CODE",
"description": "Dummy Task",
"withConfirmation": false,
"resource": {
"id": "abcdef12-fe14-57c4-acb5-1234e7456d62",
"group": "Doctor",
"firstname": "Toto",
"lastname": "Wallace",
},
{
"id": 2,
"code": "CODE",
"description": "Dummyyy Taaask",
"withConfirmation": false
}
]
}
In the returned json we have a Task which can be joined with a Resource.
In our system, a Task is as the following:
#JsonAutoDetect
public class Task implements Serializable {
private Integer id;
private String code = "BASIC";
private String description;
private boolean withConfirmation = false;
/**
* CONSTRUCTOR
*/
public Task() {
}
public Integer getId() {
return id;
}
#JsonProperty
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#JsonProperty
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#JsonProperty
public boolean isWithConfirmation() {
return withConfirmation;
}
public void setWithConfirmation(boolean withConfirmation) {
this.withConfirmation = withConfirmation;
}
public String toString() {...
}
}
and a Resource looks like that:
public class Resource implements Serializable {
...
private String firstname;
private String lastname;
private MedicalGroup group; // id + name + description
private Set<Task> tasks = new HashSet<Task>(0);
...
// getters and setters and toString etc.
...
}
So the major difference, aside from the field names is that a Task does not contain any Resource but the relation is rather in the opposite direction which means that a Resource can hold n Task.
What would be for this case the best way to serialize the returned json object from the third party and convert/map it to a pojo from my own system?
I'm currently reading Gson doc in order to try it but any suggestion is welcomed.
This code has to be easily reusable cause it's going to be needed inside multiple projects.
It is not full working code, because i have no idea how you want to work with Resource. Should Json create new resource or try to find already existing one. How will you create MedicalGroup from json, because it is not enuogh data for that. I was going to ask this in comments, but there is not enough space. And here is demo how you can try to solve most of the problems except the Resources to/from json mapping.
Main idea is to add #JsonAnyGetter public Map<String, Object> getAdditionalProperties() and #JsonAnySetter public void setAdditionalProperty(String name, Resource value) in your Task POJO:
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
HashMap<String, Object> map= new HashMap<>();
// IMPORTANT
// here we can try to find resource that has this task
// and export its info to json like this:
// CHANGE THIS
Resource res = new Resource();
res.firstname = "Toto";
res.lastname = "Wallace";
// IMPORTANT END
map.put("resource", res);
return map;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Resource value) {
// IMPORTANT
// Here you have to create or find appropriate Resource in your code
// and add current task to it
System.out.println(name+" "+ value );
}
FULL Demo:
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
public class Main3 {
private static String json = "{\n" +
" \"tasks\": [\n" +
" {\n" +
" \"id\": 1,\n" +
" \"code\": \"CODE\",\n" +
" \"description\": \"Dummy Task\",\n" +
" \"withConfirmation\": false,\n" +
" \"resource\": {\n" +
" \"id\": \"abcdef12-fe14-57c4-acb5-1234e7456d62\",\n" +
" \"group\": \"Doctor\",\n" +
" \"firstname\": \"Toto\",\n" +
" \"lastname\": \"Wallace\"\n" +
" }},\n" +
" {\n" +
" \"id\": 2,\n" +
" \"code\": \"CODE\",\n" +
" \"description\": \"Dummyyy Taaask\",\n" +
" \"withConfirmation\": false\n" +
" }\n" +
" ]\n" +
" }";
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
TasksList tl = mapper.readValue(json, TasksList.class);
String result = mapper.writeValueAsString(tl);
System.out.println(result);
}
private static class TasksList {
#JsonProperty(value = "tasks")
private List<Task> tasks;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Resource implements Serializable {
#JsonProperty(value = "firstname")
private String firstname;
#JsonProperty(value = "lastname")
private String lastname;
// HAVE NO IDEA HOW YOU GONNA MAP THIS TO JSON
// private MedicalGroup group; // id + name + description
private Set<Task> tasks = new HashSet<Task>(0);
#Override
public String toString() {
return "Resource{" +
"firstname='" + firstname + '\'' +
", lastname='" + lastname + '\'' +
", tasks=" + tasks +
'}';
}
}
#JsonAutoDetect
public static class Task implements Serializable {
private Integer id;
private String code = "BASIC";
private String description;
private boolean withConfirmation = false;
/**
* CONSTRUCTOR
*/
public Task() {
}
public Integer getId() {
return id;
}
#JsonProperty
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#JsonProperty
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#JsonProperty
public boolean isWithConfirmation() {
return withConfirmation;
}
public void setWithConfirmation(boolean withConfirmation) {
this.withConfirmation = withConfirmation;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
HashMap<String, Object> map= new HashMap<>();
// IMPORTANT
// here we can try to find resource that has this task
// and export its info to json like this:
// CHANGE THIS
Resource res = new Resource();
res.firstname = "Toto";
res.lastname = "Wallace";
// IMPORTANT END
map.put("resource", res);
return map;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Resource value) {
// IMPORTANT
// Probably here you have to create or find appropriate Resource in your code
// and add current task to it
System.out.println(name+" "+ value );
}
#Override
public String toString() {
return "Task{" +
"id=" + id +
", code='" + code + '\'' +
", description='" + description + '\'' +
", withConfirmation=" + withConfirmation +
'}';
}
}
}
you can use Gson library by google to convert Json to Pojo Class.
new Gson().fromJson(jsonString,Response.class);

How to parse JSON with Jackson that starts with "["

My string is like this:
[{"trends":[{"name":"#Happy16thPoniGoyangLimitedEditionJKT48","url":"http:\/\/twitter.com\/search?q=%23Happy16thPoniGoyangLimitedEditionJKT48","promoted_content":null,"query":"%23Happy16thPoniGoyangLimitedEditionJKT48","events":null},{"name":"#SemihVAROLTAYFAileHaftaSonuTakibi","url":"http:\/\/twitter.com\/search?q=%23SemihVAROLTAYFAileHaftaSonuTakibi","promoted_content":null,"query":"%23SemihVAROLTAYFAileHaftaSonuTakibi","events":null},{"name":"#JeeveTeriJodi","url":"http:\/\/twitter.com\/search?q=%23JeeveTeriJodi","promoted_content":null,"query":"%23JeeveTeriJodi","events":null},{"name":"#Tolga\u00D6\u011F\u00FCt\u0130leTakiple\u015Fme","url":"http:\/\/twitter.com\/search?q=%23Tolga%C3%96%C4%9F%C3%BCt%C4%B0leTakiple%C5%9Fme","promoted_content":null,"query":"%23Tolga%C3%96%C4%9F%C3%BCt%C4%B0leTakiple%C5%9Fme","events":null},{"name":"#CNEnjoyMondayyy","url":"http:\/\/twitter.com\/search?q=%23CNEnjoyMondayyy","promoted_content":null,"query":"%23CNEnjoyMondayyy","events":null},{"name":"Medha Patkar","url":"http:\/\/twitter.com\/search?q=%22Medha+Patkar%22","promoted_content":null,"query":"%22Medha+Patkar%22","events":null},{"name":"Asaram Bapuji","url":"http:\/\/twitter.com\/search?q=%22Asaram+Bapuji%22","promoted_content":null,"query":"%22Asaram+Bapuji%22","events":null},{"name":"Tune Talk","url":"http:\/\/twitter.com\/search?q=%22Tune+Talk%22","promoted_content":null,"query":"%22Tune+Talk%22","events":null},{"name":"Golden Globes 2014","url":"http:\/\/twitter.com\/search?q=%22Golden+Globes+2014%22","promoted_content":null,"query":"%22Golden+Globes+2014%22","events":null},{"name":"Game of Thrones Season 4","url":"http:\/\/twitter.com\/search?q=%22Game+of+Thrones+Season+4%22","promoted_content":null,"query":"%22Game+of+Thrones+Season+4%22","events":null}],"as_of":"2014-01-13T09:59:22Z","created_at":"2014-01-13T09:07:24Z","locations":[{"name":"Worldwide","woeid":1}]}]
I can parse this json string when I remove "[" and "]" from first and last character by following code:
private TrendTags getTrendTagsJSON(String jsonString) {
TrendTags trendTags = null;
jsonString = jsonString.substring(1, jsonString.length()-1);
try {
//create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//convert json string to object
trendTags = objectMapper.readValue(jsonString, TrendTags.class);
System.out.println(trendTags);
} catch (JsonParseException e) {
System.out.println(e.getMessage());
} catch (JsonMappingException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
return trendTags;
}
And my TrendsTag class is this:
public class TrendTags {
#JsonProperty("trends")
private Trend[] trend;
#JsonProperty("locations")
private TrendLocation[] trendLocation;
#Override
public String toString() {
return "TrendTags{" +
"trend=" + Arrays.toString(trend) +
", trendLocation=" + Arrays.toString(trendLocation) +
'}';
}
public Trend[] getTrend() {
return trend;
}
public void setTrend(Trend[] trend) {
this.trend = trend;
}
public TrendLocation[] getTrendLocation() {
return trendLocation;
}
public void setTrendLocation(TrendLocation[] trendLocation) {
this.trendLocation = trendLocation;
}
/************************
* Trend item class *
************************/
public static class Trend {
private String name;
private String url;
private String query;
#Override
public String toString() {
return "Trend {" +
"name='" + name + '\'' +
", url='" + url + '\'' +
", query='" + query + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
}
/************************
* Trend location class *
************************/
public static class TrendLocation {
private String name;
private int woeid;
#Override
public String toString() {
return "TrendLocation{" +
"name='" + name + '\'' +
", woeid=" + woeid +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWoeid() {
return woeid;
}
public void setWoeid(int woeid) {
this.woeid = woeid;
}
}
}
Since I have one object in array so it's possible to remove "[" and "]" from first and last chatacter. But this is not the solution.
My question is how to parse the json string with "[" and "]" characters? There should be a simple solution but I cannot find it. Thanks
Your JSON represents an array of your TrendTags objects. You're attempting to parse it as if it represented a single TrendTags object.
Get rid of all that code trying to modify the JSON, and just do:
TrendTags[] trendTags =
objectMapper.readValue(jsonString, TrendTags[].class);
That said, using a List is generally better;
List<TrendTags> trendTags =
objectMapper.readValue(jsonString, new TypeReference<List<TrendTags>>(){});

Categories