I'm using Spring 2.6 and we make a GET request via
restTemplate.exchange(url, HttpMethod.GET, httpEntity, ResponseType.class).getBody();
The JSON response can be of two kinds:
1st:
public class ResponseType {
private String data;
}
2nd:
public class ResponseType {
private Subclass data;
}
public class Subclass {
private String classId;
private String detail;
}
In the first version I only get a reference link to the subclass resource.
If the URL contains a 'resolve' flag, than the reference link get expanded already in the first request.
The classId then also specifies what kind of class it is ( 'a.b.c' or 'x.y.z' )
No problem for JSON, but how can I get a mapping in Java?
When having more fields being dynamic (link or instance based on classId) a manual way would be difficult to implement if the combination could be 2 links and 3 objects.
It also could be that a object has the same feature - a filed with a link or a instance of a class specified by classId.
The JSON response would be this:
{
"data": "abskasdkjhkjsahfkajdf-linkToResource"
}
or this:
{
"data": {
"classId": "a.b.subclass",
"detail": "some data"
}
}
or this:
{
"data": {
"classId": "a.b.subclass",
"detail": "some data"
"data2": "some-link-id",
"data3": {
"detailB": "foo",
"detailC": "some-link-id"
}
}
}
Here I do have a possible solution for my problem. The logic to print the address only or the POJO relies soley in the CustomItemSerializer. So it is possible to use this without using duplicate code in controllers.
package com.allianz.clana.datamodel.http.epc.test;
import java.io.IOException;
import java.text.ParseException;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import lombok.Data;
import lombok.NoArgsConstructor;
public class JacksonTester2 {
public static void main(String args[]) throws ParseException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Item item2 = new Item("link");
Stuff stuff = new Stuff();
stuff.setItem(item2);
stuff.setFoo("foo");
String jsonStringStuff = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(stuff);
System.out.println(jsonStringStuff);
Item item3 = new Item("{ \"name\":\"ID3\", \"creationDate\":\"1984-12-30\", \"rollNo\": 1 }");
stuff.setItem(item3);
stuff.setFoo("bar");
jsonStringStuff = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(stuff);
System.out.println(jsonStringStuff);
}
}
class CustomItemSerializer extends StdSerializer<Item> {
private static final long serialVersionUID = 1L;
public CustomItemSerializer() {
this(null);
}
public CustomItemSerializer(Class<Item> t) {
super(t);
}
#Override
public void serialize(Item item, JsonGenerator generator, SerializerProvider arg2) throws IOException {
if (item != null) {
if (item.getItem() != null) {
System.out.println("ItemA POJO data");
generator.writePOJO(item.getItem());
} else {
System.out.println("raw data with link");
generator.writeString(item.getRawdata());
}
}
}
}
#Data
class Stuff {
Item item;
String foo;
}
#JsonSerialize(using = CustomItemSerializer.class)
#Data
#NoArgsConstructor
class Item {
private String rawdata;
#JsonIgnore
private ItemA item;
public Item(String rawdata) {
this.rawdata = rawdata;
if (rawdata.contains("{")) {
try {
this.item = new ObjectMapper().readerFor(ItemA.class).readValue(rawdata);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
}
#Data
#NoArgsConstructor
class ItemA{
private String name;
private int rollNo;
private String creationDate;
public ItemA(String name, int rollNo, String dob) {
this.name = name;
this.rollNo = rollNo;
this.creationDate = dob;
}
}
The output looks like this:
raw data with link
{
"item" : "link",
"foo" : "foo"
}
ItemA POJO data
{
"item" : {
"name" : "ID3",
"rollNo" : 1,
"creationDate" : "1984-12-30"
},
"foo" : "bar"
}
The CustomItemSerializer decides if the link is printed or the POJO.
Related
This question already has answers here:
What is use of the annotation #JsonIgnore?
(3 answers)
Closed 5 months ago.
I have a class like
public class MyPojo {
String name,
String age
String sub
}
And map like
map("name":"john","age":21)
Using Jacksons ObjectMapper, I get a string like
{
"name": "john",
"age": "21",
"sub": null
}
but instead I want to exclude the sub:
{
"name": "john",
"age": "21"
}
How can I do that and tell Jackson to skip sub?
P.S. Please keep in mind that I want to have ability to exclude age and include sub without changing the POJO class, so #JsonIgnore doesn't quite fit.
You can use java.util.Optional in your POJO class. You can convert Map to POJO and after that serialise it ignoring null-s. Optional allows to distinguish map.put("property", null) from not setting property at all. See below example:
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class DateApp {
private final static JsonMapper JSON_MAPPER = JsonMapper.builder()
.enable(SerializationFeature.INDENT_OUTPUT)
.addModule(new Jdk8Module())
.build();
public static void main(String[] args) throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("name", "John");
map.put("age", 21);
MyPojo pojo = JSON_MAPPER.convertValue(map, MyPojo.class);
System.out.println(pojo);
System.out.println("JSON:");
JSON_MAPPER.writeValue(System.out, pojo);
}
}
#Data
#NoArgsConstructor
#AllArgsConstructor
#JsonInclude(JsonInclude.Include.NON_NULL)
class MyPojo {
private Optional<String> name;
private Optional<String> age;
private Optional<String> sub;
}
Above code prints:
MyPojo(name=Optional[John], age=Optional[21], sub=null)
JSON:
{
"name" : "John",
"age" : "21"
}
You can try this approach in order to avoid the null attributes in the final json.
I have used ObjectMapper object and set the below property to avoid null attributes in the json.
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
Code as follows:
MyPojo.java
public class MyPojo {
private String name;
private String age;
private String sub;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSub() {
return sub;
}
public void setSub(String sub) {
this.sub = sub;
}
#Override
public String toString() {
return "MyPojo{" +
"name=" + name +
", age=" + age +
", sub=" + sub +
'}';
}
}
Test.java
public class Test {
public static void main(String[] args) throws JsonProcessingException {
Map<String,String> inputMap = new HashMap<>();
inputMap.put("age","21");
inputMap.put("name","John");
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
MyPojo p = mapper.convertValue(inputMap,MyPojo.class);
System.out.println(p);
System.out.println(mapper.writeValueAsString(p));
}
}
Output:
MyPojo{name=John, age=21, sub=null}
{"name":"John","age":"21"}
You can create your custom serializer.
Just include your map in the serializer code
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
#JsonSerialize(using = MyPojoSerializer.class)
public class MyPojo {
String name;
String age;
String sub;
}
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class MyPojoSerializer extends JsonSerializer<MyPojo> {
#Override
public void serialize(MyPojo myPojo, JsonGenerator jGen, SerializerProvider serializerProvider) throws IOException {
jGen.writeStartObject();
// Map map = ....
for (final Field field : myPojo.getClass().getDeclaredFields()) {
ReflectionUtils.makeAccessible(field);
final String fieldName = field.getName();
final Object fieldValue = ReflectionUtils.getField(field, myPojo);
if (map.containsKey(fieldName)) {
jGen.writeFieldName(fieldName);
jGen.writeObject(fieldValue);
}
}
jGen.writeEndObject();
}
}
I have a JSON file
{
"readServiceAuthorizationResponse": {
"serviceAuthorization": {
"serviceAuthorizationId": "50043~220106065198",
"status": "Approved",
"receivedDate": "2022-1-6 1:21:12 PM",
"providerFirstName": "Ranga",
"providerLastName": "Thalluri",
"organizationName": "General Hospital",
"serviceLines": [{
"statusReason": "Approved",
"procedureDescription": "Room & board ward general classification",
"requestedQuantity": "1.00",
"approvedQuantity": "1.00",
"deniedQuantity": "",
"quantityUnitOfMeasure": "Day(s)",
"providers": [{
"providerFirstName": "Ranga",
"providerLastName": "Thalluri",
"organizationName": ""
}]
}]
}
}
}
My Java to read this into an object is this:
package com.shawn.dto;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
#JsonIgnoreProperties(ignoreUnknown = true)
public class ServiceAuthorizationDTO {
public String serviceAuthorizationId;
public String status;
public String receivedDate;
public String providerFirstName;
public String providerLastName;
public String organizationName;
public ServiceLine[] serviceLines;
public static ServiceAuthorizationDTO create(String json) {
ObjectMapper m = new ObjectMapper();
try {
Outer outer = m.readValue(json, Outer.class);
return outer.readServiceAuthorizationResponse.serviceAuthorization;
} catch (Exception e) {
return null;
}
}
#JsonIgnoreProperties(ignoreUnknown = true)
static class ReadServiceAuthorizationResponse {
public ServiceAuthorizationDTO serviceAuthorization;
}
#JsonIgnoreProperties(ignoreUnknown = true)
static class Outer {
public ReadServiceAuthorizationResponse readServiceAuthorizationResponse;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class ServiceLine {
String statusReason;
String procedureDescription;
String requestedQuantity;
String approvedQuantity;
String deniedQuantity;
String quantityUnitOfMeasure;
Provider[] providers;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Provider {
String providerFirstName;
String providerLastName;
String organizationName;
}
public static void main(String[] args) {
try {
String json = new String(Files.readAllBytes(Paths.get("c:/temp/test.json")));
ServiceAuthorizationDTO dao = ServiceAuthorizationDTO.create(json);
System.out.println("serviceAuthorizationId: " + dao.serviceAuthorizationId);
System.out.println("serviceLines[0].procedureDescription: " + dao.serviceLines[0].procedureDescription);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
When I run it I get this:
serviceAuthorizationId: 50043~220106065198
serviceLines[0].procedureDescription: null
The outer fields in the object like providerId are read from the JSON. But the serviceLines array shows 1 element, and all fields in that class are empty.
Any ideas? This is the first time I've used real objects with JSON. I've always mapped it into Map objects and pulled the fields out manually. Thanks.
Fields in classes ServiceLine and Provider have package-private access modifiers. Jackson can't deserialize into private fields with its default settings. Because it needs getter or setter methods.
Solution 1: Make fields public
public static class ServiceLine {
public String statusReason;
public String procedureDescription;
public String requestedQuantity;
public String approvedQuantity;
public String deniedQuantity;
public String quantityUnitOfMeasure;
public Provider[] providers;
}
Solution 2: Use #JsonAutoDetect annotation
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class ServiceLine {
String statusReason;
String procedureDescription;
String requestedQuantity;
String approvedQuantity;
String deniedQuantity;
String quantityUnitOfMeasure;
Provider[] providers;
}
Solution 3: Change visibility on the ObjectMapper (doc)
public static ServiceAuthorizationDTO create(String json) {
ObjectMapper objectMapper = new ObjectMapper();
try {
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
Outer outer = objectMapper.readValue(json, Outer.class);
return outer.readServiceAuthorizationResponse.serviceAuthorization;
} catch (Exception e) {
return null;
}
}
I'm trying to create a java model for my json response in a melanoma detection app.
My response looks like this:
{
"success": true,
"predictions": [
{
"label": "Non-melanoma",
"probability": 0.016881238669157028
},
{
"label": "Melanoma",
"probability": 0.9831187129020691
}
]
}
I usually go with https://www.jsonschema2pojo.org/ in creating my java model from json, but this time I am getting this:
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
#Generated("jsonschema2pojo")
public class Example {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("predictions")
#Expose
private List<Prediction> predictions = null;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public List<Prediction> getPredictions() {
return predictions;
}
public void setPredictions(List<Prediction> predictions) {
this.predictions = predictions;
}
}
-----------------------------------com.example.Prediction.java-----------------------------------
package com.example;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
#Generated("jsonschema2pojo")
public class Prediction {
#SerializedName("label")
#Expose
private String label;
#SerializedName("probability")
#Expose
private Double probability;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Double getProbability() {
return probability;
}
public void setProbability(Double probability) {
this.probability = probability;
}
}
which leads to different files that I don't know how to use later.
I'd like to have one response model, like response_model.java to use like this in the app:
Call<response_model> call = getResponse.uploadFile(fileToUpload, filename);
call.enqueue((Callback<response_model>)(new Callback<response_model>() {
public void onResponse(#NotNull Call call, #NotNull Response response) {
Intrinsics.checkParameterIsNotNull(call, "call");
Intrinsics.checkParameterIsNotNull(response, "response");
if (response.isSuccessful()) {
Log.v("upload", "response succ");
response_model serverResponse = (response_model) response.body();
if (serverResponse.getPredictions()!=null) {
((TextView)findViewById(R.id.output_text)).setText(serverResponse.getPredictions().toString());
} else {
loader.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "response null",Toast.LENGTH_SHORT).show();
}
} else {
Log.v("Response 1", "wasnt successfull");
}
}
Is there a way?
Actually your java model is working just fine.
You can access each label/probability as a list element, by:
serverResponse.getPredictions().get(0).getLabel()
serverResponse.getPredictions().get(0).getProbability()
(which should give you the 1st Label-Probability element pair).
If you're always gonna have 2 elements in your response Prediction list (one for melanoma and one for non-melanoma) you can easily hard-code it with get(0) and get(1).
You can use this link to generate pojo
https://json2csharp.com/json-to-pojo
This is how your pojo will looks like in a single file
package com.test.test;
import java.util.List;
class Prediction{
public String label;
public double probability;
}
public class Test{
public boolean success;
public List<Prediction> predictions;
}
With Spring Boot and Jackson, how can I deserialize a wrapped/inner list into a list directly in the outer level?
For example, I have:
{
"transaction": {
"items": {
"item": [
{
"itemNumber": "193487654",
"itemDescription": "Widget",
"itemPrice": "599.00",
"itemQuantity": "1",
"itemBrandName": "ACME",
"itemCategory": "Electronics",
"itemTax": "12.95"
},
{
"itemNumber": "193487654",
"itemDescription": "Widget",
"itemPrice": "599.00",
"itemQuantity": "1",
"itemBrandName": "ACME",
"itemCategory": "Electronics",
"itemTax": "12.95"
}
]
},
...
}
}
In the JSON, item is a list under items; but I want to parse it as a list named items, directly under transaction, instead of defining a DTO Items which contains a list named item.
Is this possible? How to define this DTO Item?
public class TrasactionDTO {
private List<Item> items;
...
}
public class Item {
}
This question is similar but does not solve the problem.
Deserialize wrapped list using Jackson
We need to implement custom deserialiser. Because we want to skip one inner field our implementation should:
{ - skip start object
"any_field_name" - skip any field name. We assume that we have only one inner field.
[{}, ..., {}] - use default deserialiser for List.
} - skip end object
Using above concept implementation should be easy:
public class InnerListDeserializer extends JsonDeserializer<List> implements ContextualDeserializer {
private final JavaType propertyType;
public InnerListDeserializer() {
this(null);
}
public InnerListDeserializer(JavaType propertyType) {
this.propertyType = propertyType;
}
#Override
public List deserialize(JsonParser p, DeserializationContext context) throws IOException {
p.nextToken(); // SKIP START_OBJECT
p.nextToken(); // SKIP any FIELD_NAME
List list = context.readValue(p, propertyType);
p.nextToken(); // SKIP END_OBJECT
return list;
}
#Override
public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) {
return new InnerListDeserializer(property.getType());
}
}
Let's assume we have JSON payload like this:
{
"transaction": {
"items": {
"item": [
{
"itemNumber": "193487654",
"itemDescription": "Widget",
"itemPrice": "599.00",
"itemQuantity": "1",
"itemBrandName": "ACME",
"itemCategory": "Electronics",
"itemTax": "12.95"
},
{
"itemNumber": "193487654",
"itemDescription": "Widget",
"itemPrice": "599.00",
"itemQuantity": "1",
"itemBrandName": "ACME",
"itemCategory": "Electronics",
"itemTax": "12.95"
}
]
},
"name": "Pickle Rick"
}
}
Above JSON we can map to below POJO classes:
#JsonRootName("transaction")
public class Transaction {
private String name;
private List<Item> items;
#JsonDeserialize(using = InnerListDeserializer.class)
public List<Item> getItems() {
return items;
}
// getters, setters, toString
}
public class Item {
private String itemNumber;
// getters, setters, toString
}
To show it works for many different models let's introduce one more JSON payload:
{
"product": {
"products": {
"innerArray": [
{
"id": "1234"
}
]
}
}
}
and two more POJO classes:
#JsonRootName("product")
class Product {
private List<ProductItem> products;
#JsonDeserialize(using = InnerListDeserializer.class)
public List<ProductItem> getProducts() {
return products;
}
// getters, setters, toString
}
class ProductItem {
private String id;
// getters, setters, toString
}
Now we can test our solution:
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class JSoupTest {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
File jsonFile = new File("Path to 1-st JSON").getAbsoluteFile();
File jsonFile1 = new File("Path to 2-nd JSON").getAbsoluteFile();
System.out.println(mapper.readValue(jsonFile, Transaction.class));
System.out.println(mapper.readValue(jsonFile1, Product.class));
}
}
Above example prints:
Transaction{items=[Item{itemNumber=193487654}, Item{itemNumber=193487654}], name='Pickle Rick'}
Product{products=[ProductItem{id='1234'}]}
For more info read:
Custom Jackson Deserializer Getting Access to Current Field Class
Getting Started with Custom Deserialization in Jackson
Jackson Exceptions – Problems and Solutions
Jackson UNWRAP_ROOT_VALUE
Configuring ObjectMapper in Spring
It seems that #JsonUnwrapped is what I need.
https://www.baeldung.com/jackson-annotations
#JsonUnwrapped defines values that should be unwrapped/flattened when serialized/deserialized.
Let's see exactly how that works; we'll use the annotation to unwrap the property name:
public class UnwrappedUser {
public int id;
#JsonUnwrapped
public Name name;
public static class Name {
public String firstName;
public String lastName;
}
}
Let's now serialize an instance of this class:
#Test
public void whenSerializingUsingJsonUnwrapped_thenCorrect()
throws JsonProcessingException, ParseException {
UnwrappedUser.Name name = new UnwrappedUser.Name("John", "Doe");
UnwrappedUser user = new UnwrappedUser(1, name);
String result = new ObjectMapper().writeValueAsString(user);
assertThat(result, containsString("John"));
assertThat(result, not(containsString("name")));
}
Here's how the output looks like – the fields of the static nested class unwrapped along with the other field:
{
"id":1,
"firstName":"John",
"lastName":"Doe"
}
So, it should be something like:
public class TrasactionDTO {
private List<Item> items;
...
}
public static class Item {
#JsonUnwrapped
private InnerItem innerItem;
...
}
public static class InnerItem {
private String itemNumber;
...
}
You can use a Map to represent the intermediate Items object.
Given this example (all fields public just for demonstration purposes):
public class Item {
public String itemNumber, itemDescription, itemPrice, itemQuantity, itemBrandName, itemCategory, itemTax;
}
...you can achieve what you want in two ways:
1. By using a constructor:
public class TransactionDTO {
private List<Item> items;
#JsonCreator
public TransactionDTO(#JsonProperty("items") final Map<String, List<Item>> items) {
this.items = items.get("item");
}
}
2. By using a setter:
public class TransactionDTO {
private List<Item> items;
public void setItems(final Map<String, List<Item>> items) {
this.items = items.get("item");
}
}
While assigning values from DTO to different entity names, I assigned correctly with the help of JsonProperty. FrontEnd expecting in a different name. Values for DTO object will get from different object. That I have to assign to entity. Instead of using plain java and copying, am using objectmapper. Here then entity values will be used by frontend. How to print the entity values in different name? Please check below code.
//DTO Class
import java.util.List;
public class StaffDTO {
private String nameDT;
private List<String> skillDT;
//Getter and Setters
}
//Entity Class
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"nameDT",
"skillDT"
})
public class Staff {
#JsonProperty("nameDT")
private String name;
#JsonProperty("skillDT")
private List<String> skills;
//Getter and Setters
}
//Call Method
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class SeatMapCall1 {
public static void main(String[] args) {
try {
StaffDTO staffDTO = createDummyObject();
System.out.println(convertObjectToJson(staffDTO));
Staff staff= convertJsonToObject(convertObjectToJson(staffDTO),Staff.class);
System.out.println(convertObjectToJson(staff));
} catch (Throwable e) {
e.printStackTrace();
}
}
private static <T> T convertJsonToObject(String jsonStrRes,
Class<T> classArg) {
T resObj = null;
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
resObj = mapper.readValue(jsonStrRes, classArg);
} catch (Throwable e) {
e.printStackTrace();
}
return resObj;
}
public static <T> String convertObjectToJson(T obj) {
String jsonStringReq = null;
ObjectMapper objMapper = new ObjectMapper();
try {
jsonStringReq = objMapper.writeValueAsString(obj);
} catch (Exception e) {
}
return jsonStringReq;
}
private static StaffDTO createDummyObject() {
StaffDTO staffDTO = new StaffDTO();
staffDTO.setNameDT("mkyong");
List<String> skills = new ArrayList<>();
skills.add("java");
skills.add("python");
staffDTO.setSkillDT(skills);
return staffDTO;
}
}
//Displays output as
{"nameDT":"mkyong","skillDT":["java","python"]}
{"nameDT":"mkyong","skillDT":["java","python"]}
But I want
{"nameDT":"mkyong","skillDT":["java","python"]}
{"name":"mkyong","skills":["java","python"]}
If I use the below getter and setters in Staff class, I am getting expected as below
{"nameDT":"mkyong","skillDT":["java","python"]}
{"nameDT":"mkyong","skillDT":["java","python"],"name":"mkyong","skills":["java","python"]}
Here it includes both nameDT, skillDT and name, skills. I don't need nameDT, skillDT.
#JsonProperty("nameDT")
private String nameDT;
#JsonProperty("skillDT")
private List<String> skillDT;
public String getName()
{ return nameDT; }
public void setName(String nameDT)
{ this.nameDT = nameDT; }
public List<String> getSkill()
{ return skillDT; }
public void setSkill(List<String> skillDT)
{ this.skillDT = skillDT; }