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);
Related
I'm making a Shopping app which gets product attributes from the server. The Json Array I get from the server contains nested Json objects and Json arrays which look likes this:
[
"id": 1860,
"name": "T-Shirt",
"attributes": [
{
"id": 1,
"name": "color",
"position": 0,
"visible": true,
"variation": false,
"options": [
"blue",
"green",
"red"
]
},
{
"id": 2,
"name": "size",
"position": 3,
"visible": true,
"variation": false,
"options": [
"L",
"M",
"XL",
"XXL"
]
}
],
I created a class for managing product variables which contains of strings and ints and setters and getters for simple variable types like name,price etc.
public class Product {
//a class holding product objects for managing through app
public void setProductName(String productName) {
this.productName = productName;
}
private String productName;
private String productPrice;
private String oldPrice;
private int attrCount;
HashMap<String, ArrayList<String>> attrs;
private String description;
private boolean isLoading = false;
private boolean isNew = false;
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
private String imageUrl="";
public Product( String productName, String productPrice, boolean isNew,String imageUrl) {
this.productName = productName;
this.productPrice = productPrice;
this.isNew = isNew;
this.imageUrl=imageUrl;
}
public Product() {
}
public boolean isNew() {
return isNew;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public String getProductName() {
return productName;
}
But for managing attributes I need a way to bind each attribute name with its options to keep track of them in future.
Because the attributes and options coming from the server are varied each time I can't use something like enums.
I tried to store the data using HashMap<String,ArrayList> in my products class which takes the attribute as a key and option arrays as values.
HashMap<String,ArrayList<String>>attrs=new HashMap<>();
for (int j=0;j<attrJsonArray.length();j++){
JSONArray optionJsonArray=new JSONArray(attrJsonArray.getJSONObject(j).getString("options"));
ArrayList<String>attrsOptionArray= new ArrayList<>();
for(int k=0;k<optionJsonArray.length();k++){
attrsOptionArray.add(optionJsonArray.getString(k));
}
attrs.put(attrJsonArray.getJSONObject(j).getString("name"),attrsOptionArray);
}
but it seems like a bad practice. I wonder what is the right way to store this kind of data.
You can parse json to java class.
1.Use com.fasterxml.jackson.databind.ObjectMapper for parsing json.
com.fasterxml.jackson.databind.ObjectMapper objectMapper = new ObjectMapper();
Product product = objectMapper.readValue(dataOfJson, Product.class);
2.Make java class for json.
Key of json is field name or name of #JsonProperty.
Array of json is List or array.
If exist The deeper field like "attributes",Use nested static class.
class Product {
#JsonProperty("name")
private String productName;
private String id;
... other field
private List<Attributes> attributes;
// set and get method
static class Attributes{
private String id;
private List<String> options;
... other field
//set and get method
}
}
If you want to try testing, Use this. But I changed a little your json because Your json is not completed.
public class JsonToPojo {
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
String dataOfJson = " {\r\n"
+ " \"id\": 1860,\r\n"
+ " \"name\": \"T-Shirt\",\r\n"
+ "\r\n"
+ " \"attributes\": [{\r\n"
+ " \"id\": 1,\r\n"
+ " \"name\": \"color\",\r\n"
+ " \"position\": 0,\r\n"
+ " \"visible\": true,\r\n"
+ " \"variation\": false,\r\n"
+ " \"options\": [\r\n"
+ " \"blue\",\r\n"
+ " \"green\",\r\n"
+ " \"red\"\r\n"
+ " ]\r\n"
+ " },\r\n"
+ "\r\n"
+ " {\r\n"
+ " \"id\": 2,\r\n"
+ " \"name\": \"size\",\r\n"
+ " \"position\": 3,\r\n"
+ " \"visible\": true,\r\n"
+ " \"variation\": false,\r\n"
+ " \"options\": [\r\n"
+ " \"L\",\r\n"
+ " \"M\",\r\n"
+ " \"XL\",\r\n"
+ " \"XXL\"\r\n"
+ " ]\r\n"
+ " }\r\n"
+ " ]\r\n"
+ "}";
com.fasterxml.jackson.databind.ObjectMapper objectMapper = new ObjectMapper();
Product product = objectMapper.readValue(dataOfJson, Product.class);
System.out.println(product);
}
}
class Product {
#JsonProperty("name")
private String productName;
private String id;
private List<Attributes> attributes;
static class Attributes{
private String id;
private String name;
private int position;
private boolean visible;
private boolean variation;
private List<String> options;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public boolean isVariation() {
return variation;
}
public void setVariation(boolean variation) {
this.variation = variation;
}
public List<String> getOptions() {
return options;
}
public void setOptions(List<String> options) {
this.options = options;
}
#Override
public String toString() {
return "Attributes [id=" + id + ", name=" + name + ", position=" + position + ", visible=" + visible
+ ", variation=" + variation + ", options=" + options + "]";
}
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Attributes> getAttributes() {
return attributes;
}
public void setAttributes(List<Attributes> attributes) {
this.attributes = attributes;
}
#Override
public String toString() { // for printing output
return "Product [productName=" + productName + ", id=" + id + ", attributes=" + attributes + "]";
}
}
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];
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 + '\'' +
'}';
}
}
}
The error code :
org.codehaus.jackson.map.exc.UnrecognizedPropertyException:
Unrecognized field "id" (Class JacksonTester$Student), not
marked as ignorable
at [Source: [B#40334c25; line: 2, column: 8]
(through reference chain: Student["id"])
I have the below JSON file:
{
"id": "0",
"title": "0",
"externalId": "0",
"externalLink": "0",
"sourceApplication": "0",
"content": "0",
"summaryContent": "0",
"publishedDate": "0",
"harvestDate": "0",
"languageId": "0",
"regionId": "0",
"postStatus": "0"
}
and my code is
JacksonTester.java:
public class JacksonTester {
public static void main(String args[]) {
ObjectMapper mapper = new ObjectMapper();
// map json to student
try {
byte[] jsonData = Files.readAllBytes(Paths.get("output_json.txt"));
Student student = mapper.readValue(jsonData, Student.class);
System.out.println(student);
} catch (Exception e) {
e.printStackTrace();
}
}
static class Student {
String id;
String title;
String externalId;
String externalLink;
String sourceApplication;
String content;
String summaryContent;
String publishedDate;
String harvestDate;
String languageId;
String regionId;
String postStatus;
public Student() {
}
}
}
You need to either have setters for those fields or a constructor that accepts those fields as parameters (+ approriate annotations or -parameters from Java 8 and jackson-module-parameter-names
module):
public static class Student {
...
String postStatus;
public setPostStatus(postStatus) {
this.postStatus = postStatus;
}
...
}
Jackson has no access to the fields of Student.
Implement the public getters and setters for Student and it works.
I sorted this problem and it's working fine. Here is my code for the same.
**MainClass.java:**
public class MainClass {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String jsonStr = "{\r\n" + " \"id\": \"168\",\r\n" + " \"title\": \"Mr\",\r\n"
+ " \"externalId\": \"247518\",\r\n" + " \"externalLink\": \"www.gmail.com\",\r\n"
+ " \"sourceApplication\": \"adsense\",\r\n" + " \"content\": \"hmtl\",\r\n"
+ " \"summaryContent\": \"null\",\r\n" + " \"publishedDate\": \"12122018\",\r\n"
+ " \"harvestDate\": \"12122018\",\r\n" + " \"languageId\": \"3\",\r\n" + " \"regionId\": \"45\",\r\n"
+ " \"postStatus\": \"1\"\r\n" + "}";
ObjectMapper mapper = new ObjectMapper();
MyPojo details = mapper.readValue(jsonStr, MyPojo.class);
System.out.println("Value for getId is: " + details.getId());
System.out.println("Value for getSourceApplication is: " + details.getSourceApplication());
System.out.println("Value for getExternalId is: " + details.getPublishedDate());
System.out.println("Value for getExternalLink is: " + details.getExternalLink());
} }
**MyPojo.class**
public class MyPojo {
private String content;
private String id;
private String sourceApplication;
private String title;
private String postStatus;
private String publishedDate;
private String summaryContent;
private String harvestDate;
private String languageId;
private String externalId;
private String regionId;
private String externalLink;
public String getContent() {
return content;
}
public String getId() {
return id;
}
public String getSourceApplication() {
return sourceApplication;
}
public String getTitle() {
return title;
}
public String getPostStatus() {
return postStatus;
}
public String getPublishedDate() {
return publishedDate;
}
public String getSummaryContent() {
return summaryContent;
}
public String getHarvestDate() {
return harvestDate;
}
public String getLanguageId() {
return languageId;
}
public String getExternalId() {
return externalId;
}
public String getRegionId() {
return regionId;
}
public String getExternalLink() {
return externalLink;
} }
**RESULT:**
Value for getId is: 168
Value for getSourceApplication is: adsense
Value for getExternalId is: 12122018
Value for getExternalLink is: www.gmail.com
NOTE
One has to change the fields in the json to begin with a lower case letter. The reason for the JSON change is that the Jackson bean serialisation will reflect over the class, and when it sees getXyz() and setXyz() methods will map these to a Json filed names "xyz" (and not "Xyz").I think there are several ways to override this behaviour, one is to use the one of the Jackson annotations.
Instead of creating so many public getters, you could simply modify private variables to public
I have a String with the following value:
[
{
"key1": "value11",
"key2": "value12"
},
{
"key1": "value21",
"key2": "value22"
}
]
And the following class:
public class SomeClass {
private String key1;
private String key2;
/* ... getters and setters omitted ...*/
}
And I want to parse it to a List<SomeClass> or a SomeClass[]
Which is the simplest way to do it using Jackson ObjectMapper?
I finally got it:
ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<SomeClass> someClassList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class));
The other answer is correct, but for completeness, here are other ways:
List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);
The complete example with an array.
Replace "constructArrayType()" by "constructCollectionType()" or any other type you need.
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
public class Sorting {
private String property;
private String direction;
public Sorting() {
}
public Sorting(String property, String direction) {
this.property = property;
this.direction = direction;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public static void main(String[] args) throws JsonParseException, IOException {
final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
ObjectMapper mapper = new ObjectMapper();
Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));
System.out.println(sortings);
}
}
I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.
Main Class:-
String jsonStr = "[{\r\n" + " \"name\": \"John\",\r\n" + " \"city\": \"Berlin\",\r\n"
+ " \"cars\": [\r\n" + " \"FIAT\",\r\n" + " \"Toyata\"\r\n"
+ " ],\r\n" + " \"job\": \"Teacher\"\r\n" + " },\r\n" + " {\r\n"
+ " \"name\": \"Mark\",\r\n" + " \"city\": \"Oslo\",\r\n" + " \"cars\": [\r\n"
+ " \"VW\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n"
+ " \"job\": \"Doctor\"\r\n" + " }\r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);
for (MyPojo itr : jsonObj) {
System.out.println("Val of getName is: " + itr.getName());
System.out.println("Val of getCity is: " + itr.getCity());
System.out.println("Val of getJob is: " + itr.getJob());
System.out.println("Val of getCars is: " + itr.getCars() + "\n");
}
POJO:
public class MyPojo {
private List<String> cars = new ArrayList<String>();
private String name;
private String job;
private String city;
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} }
RESULT:-
Val of getName is: John
Val of getCity is: Berlin
Val of getJob is: Teacher
Val of getCars is: [FIAT, Toyata]
Val of getName is: Mark
Val of getCity is: Oslo
Val of getJob is: Doctor
Val of getCars is: [VW, Toyata]