How to save array of objects into DTO class - json

So I have passed data in ajax as:
{
“name” : “Rahul”,
“age” : “23”,
“information” : [
{
“id” : “901”,
“role” : “developer”
}
],
“salary” : “21000”,
}
For this I have created two DTO classes as
class EmployeeDTO {
#SerializedName(“name”)
private String name;
#SerializedName(“age”)
private String age;
#SerializedName(“information”)
private List<InformationDTO> informationDto;
#SerializedName(“Salary”)
private String salary;
//Their getters and setters
}
I mentioned List because I took information as an array of objects. Then I have another DTO class
class InformationDTO {
#SerializedName(“id”)
private String id;
#SerializedName(“role”)
private String role;
}
Now in my Sling Servlet I am trying to get values of information array like
String information = request.getParameter(“information”);
But I am getting null value. How can I store this array information in my DTO class Employee using InformationDTO?
How to save array of objects into DTO class using sling servlet?

Related

spring boot json to model conversion error

{
"cust":"A",
"del":[{
"type1": "id",
"type2":[{
"name":"address"
}]
}]
I have converted this json to below model class
public class Del{
public String type1;
public JSONArray type2; // "type2" has dynamic key and value which are string, it can have "name":"address","id":"sal" pair etc dynamically
}
public class Root{
public String cust;
public List<Del> del;
}
But, this mapping is showing error. how to fetch key and value inside "type2" in dynamic way where attribute names are not fixed.
If you have a list, you need a List<T>. What is T? If it can have any number of keys, then it must be a Map<K, V>. K is String, and V is either String or Object, depending on your actual structure. If you have a handful of expected keys and want to ignore everything else, make T a custom class of yours:
class Type2Props {
public String name;
public String address;
public String id;
public String sal;
}
Properties/fields without a value in the JSON will be left initialized as null.
Putting it together, you either need
public class Del {
public String type1;
public List<Type2Props> type2;
}
or
public class Del {
public String type1;
public List<Map<String, String>> type2; /* might be `Map<String, Object>` */
}

How to combine #JsonView with #JsonProperty?

I have a DTO class that should serve json via a spring-mvc #RestController.
I want to provide different version/views on the same object. Especially, there are fields that are only used in VERSION_1 of the api, and some only in VERSION_2.
Problem: I could add #JsonView for this, but my goal is also to rename those fields. Some fields should actually replace the same name from previous versions.
Example:
public class Person {
#JsonView(View.Version_1.class)
#JsonProperty("name")
private String name; //eg only the firstname
#JsonView(View.Version_2.class)
#JsonProperty("name")
private NameDTO namedto; //now changing to first+last name
static class NameDTO {
private String firstname;
private String lastname;
}
}
#RestController
public class MyServlet {
#GetMapping("/person/{id}")
#JsonView(View.Version_1.class)
public PersonDTO person1(int id) {
//...
}
#GetMapping("/person_new/{id}")
#JsonView(View.Version_2.class)
public PersonDTO person2(int id) {
//...
}
}
So, depending on the view/version, you would get the same json field firstname, but with different content.
In this example, using V1 would give:
{"name": "john"}
Whereas using V2 should result in:
{"name": {"firstname": "john", "lastname": "doe"}}
BUT not with he code above, as jackson complains:
com.fasterxml.jackson.databind.JsonMappingException: Conflicting
getter definitions for property "name".
Is that possible at all?
I found a way using:
https://github.com/jonpeterson/spring-webmvc-model-versioning
Basic idea is to add a custom VersionedModelConverter that is applied on #VersionedModelConverter annotated webservice response classes.
#Configuration
#Import(VersionedModelResponseBodyAdvice.class)
public class SpringMvcVersioningConfiguration {
//register in jackson. spring-boot automatically registers any module beans
#Bean
public Model versioningModel() {
return new VersioningModule();
}
}
#GetMapping
#VersionedResponseBody(defaultVersion = "2.0")
public Person person() {
}
#JsonVersionedModel(currentVersion = "3.0" toPastConverterClass = PersonConverter.class)
public class Person {
}
public class PersonConverter implements VersionedModelConverter {
#Override
public ObjectNode convert(ObjectNode modelData, String modelVersion, String targetModelVersion, JsonNodeFactory nodeFactory) {
Double modelv = Double.valueOf(modelVersion);
Double targetv = Double.valueOf(targetVersion);
//todo if-else based on model version
Object node = modelData.remove("fieldname");
//node.change...
modelData.set("fieldname_renamed", node);
}
}

Type of data received from AngularJS POST?

I send json Object from AngularJS POST
(json['name']="Name";json['lastName']="LastNAme");
In Spring mvc Controller I got this message
"name=Name&lastName=LastName"
I don't know the type of this message, whether it is JSON or String and how to parse to a java object.
Create a model representating your JSON object.
public class Person{
private String name;
private String lastname;
//...Setters + Getters + default constructor
}
Then in your controller handler :
#Controller
//Mapping here
public class YourController{
#PostMapping
public void getPerson(#RequestBody Person person){
//process here
}
}

how to add custom objectMapper for a specific spring rest controller

I have two controllers in my micro service both are POST and accepts Request body as JSON, one is working fine and another one's JSON input from some othet team and it is with root class name , so I need to write custom object mapper for this later controller, could you please guys help,
please find the codes below,
#RestController
#Slf4j
public class Controller2 {
#RequestMapping(value = "/some/update", method = RequestMethod.POST)
public String updateEmd(#RequestBody final UpdateEMDRequest updateEMDRequest) throws JsonProcessingException {
updateEMDRequest.getBookingReference()); // null now
return "success";
}
}
and the sample json is as follows,
{
"UpdateEMDRequest":{
"TransactionStatus":"SUCCESS",
"UniqueTransactionReference":"046060420",
"PreAuthReference":"040520420",
"BookingReference":"8PJ",
"CarrierCode":"AS",
"TransactionMode":"Batch",
"CallBackUrl":"www.test.com/op/update",
"Offers":[
{
"Offer":{
"traveler":{
"firstName":"AHONY",
"surname":"DNEN",
"EMD":[
"081820470"
]
}
}
}
]
}
}
UpdateEMDRequest,java
#JsonInclude(Include.NON_NULL)
public class UpdateEMDRequest {
#JsonProperty("UniqueTransactionReference")
private String uniqueTransactionReference;
#JsonProperty("TransactionStatus")
private String transactionStatus;
#JsonProperty("PreAuthReference")
private String preAuthReference;
#JsonProperty("BookingReference")
private String bookingReference;
#JsonProperty("CarrierCode")
private String carrierCode;
#JsonProperty("TransactionMode")
private String transactionMode;
#JsonProperty("CallBackUrl")
private String callBackUrl;
#JsonProperty("Offers")
private List<Offers> offers;
}
So this json is not parsed properly and updateEMDRequest's properties are null always.

Mapping JSON to POJO not working

I have a spring MVC project,in the controller i have the following method :
#RequestMapping(value = IdentityServiceURIConstants.CREATE_NEW_USER, method = RequestMethod.POST)
public #ResponseBody User createUser(#RequestBody User user) {----}
this method receives a JSON object which is supposed to represent the user object.
My problem is that the fields in the user object are not identical to those received in the JSON object.
Example: first name is First_Name in JSON and firstName in object, hence, the mapping is not working.
Do u have any idea on how to solve this problem, given that i cant edit neither the user object nor the JSONobject
You can use #JsonProperty to name your java class property to the json key name like below:
import com.fasterxml.jackson.annotation.JsonProperty;
public class User {
#JsonProperty("FIRST_NAME")
private String firstName;
#JsonProperty("LAST_NAME")
private String lastName;
// getters & Setters methods
}
and your json will be something like this:
{
"FIRST_NAME": "first name",
"SECOND_NAME": "second name"
}
You can write a DTO class.
class UserDTO{
private User user;
// use getter setter to extract data from object
}