I'm trying to map two fields from Java POJO to one json field;
public class Person {
private String firstName;
//this two fields should be in separate json property (object)
private String street;
private String streetNo;
...
//getters and setters
}
And I want to get response something like this:
{
firstName: "Peter",
address: {
street: "Square nine",
streetNumber: "12"
}
}
You should implement then another POJO Address and add address field to your Person POJO
public class Person {
private String firstName;
private Address address = new Address();
...
//getters and setters
}
// another POJO
public class Address {
private String street;
private String streetNo;
//getters and setters
}
Related
I am facing issue when I am trying to use ModelMapper to convert nested java objects into nested DTO's. Getting null for child dto's in parent dto object. Following are the code snippets.
Entity Classes :
public class User {
private String name;
private Address address;
private Product product;
}
public class Address {
private String area;
private String city;
}
public class Product {
private Integer productId;
private String productName;
private Double productPrice;
}
DTO's Classes :
public class UserDTO {
private String name;
private AddressDTO address;
private ProductDTO product;
}
public class AddressDTO {
private String area;
private String city;
}
public class ProductDTO {
private Integer productId;
private String productName;
private Double productPrice;
}
here is the mapper code :
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
UserDTO userDTO = mapper.map(user, UserDTO.class);
System.out.println("Output User DTO : " + userDTO );
Output :
Output User DTO : UserDTO [name=xyz, address=null, product=null]
Here I want to convert User entity into UserDTO dto.
I am getting null values for address and product DTO's. What exactly I am missing here ? Does anyone have any idea ?
Note : I have added getters, Setters and toString() methods in entity and DTO's.
Here I found solution for nested DTO to Entity and vice versa conversions, I was missing some ModelMapper configurations that I have added below.
mapper.getConfiguration()
.setFieldMatchingEnabled(true)
.setFieldAccessLevel(AccessLevel.PRIVATE)
.setMatchingStrategy(MatchingStrategies.STANDARD);
I am struggling to map a string object from source(Relation.class) and to a List of target(RelationListDTO.class) .
Relation.java
public class Relation {
private String name;
private String email;
private String completeAddress;
// getters and setters
}
RelationListDTO.java
public class RelationListDTO {
private String name;
private String email;
private List<Address> address;
// getters and setters
}
Address.java
public class Address{
private String street;
private String city;
// getters and setters
}
Mapper class
#Mapper
public interface RelationMapper {
#Mapping(source = "completeAddress", target = "address.get(0).city")
RelationListDTO relationToListDto(Relation relation);
}
But it is not working. Could anyone please help.
What you are trying to do using MapStruct is not possible. Because MapStruct doesn't work with run time objects. MapStruct only generated plain java code for mapping two beans. And I find your requirement is little unique. You have a list of Addresses but want to map only city from source object? You can still do like this
#Mapping( target = "address", source = "completeAddress")
RelationListDTO relationToListDto(Relation relation);
// MapStruct will know to use this method to map between a `String` and `List<Address>`
default List<Address> mapAddress(String relation){
//create new arraylist
// create new AddressObject and set completeAddress to address.city
// add that to list and return list
}
Not sure if this was possible at the time of the accepted answer but I had the same problem as you and ended up doing it this way.
#Mapper(imports = Collections.class)
public interface RelationMapper {
#Mapping(expression = "java(Collections.singletonList(relation.getCompleteAddress()))", target = "address")
RelationListDTO relationToListDto(Relation relation);
}
In the code below, class Address is nested in Entity User. I wonder if all the attributes of Address are private, do we need getter and setter for each of the field in Address? Notice there is a List<String>, so I'm not sure if Room will work well with #TypeConverter in this case.
public class Address {
public String street;
public String state;
public List<String> city;
#ColumnInfo(name = "post_code")
public int postCode;
}
#Entity
public class User {
#PrimaryKey
public int id;
public String firstName;
#Embedded
public Address address;
}
You can easily add getter/setters with #Ignore annotation and the converter will ignore these methods.
#Ignore
public List<String> getCity() {
return city;
}
You can refer here
Create the entity
I'm working with java project using spring REST.
My problem that i could not extract data from request body (which is json) after receive it as enitiy.
for example:
JSON Request Body
{
"firstname": "Rayan",
"lastname": "Cold",
"company_id": 23
}
My Controller maaped method is:
#PostMapping("/employee")
public Employee createEmployee(#RequestBody Employee employee) {
// Here i need to extract the company id from request body
// Long companyId = *something* // how i can extract from request ?
return companiesRepository.findById(companyId).map(company -> {
employee.setCompany(company);
return employeeRepository.save(employee);
}).orElseThrow(() -> new ResourceNotFoundException("Company not found"));
}
I know i can pass company ID as path variable. But i do want it in request body not in URI.
Thanks
company_id can not be mapped if your Employee class contains companyId.
I guess your company class like:
public class Employee {
private String firstname;
private String lastname;
private Long companyId;
//skip getter setter
}
change it to :
public class Employee {
private String firstname;
private String lastname;
#Transient
#JsonProperty("company_id")
private Long companyId;
//skip getter setter
}
You can simply take the company id from the object received:
employee.getCompany_id();
Please ensure, your Employee class should be something like below:
public class Employee
{
private String company_id;
private String lastname;
private String firstname;
// getter and setters of all these member fields
}
Name of the variables should be same as the one in JSON or use the
appropriate annotations.
Can any one help me out in this , i'm new to JSON . The problem is that i want to map a single json objects Keys values pair to three different java classes?
{"firstName":"Sasi","lastName":"Dunston","jobTitle":"Trainee","dateOfBirth":"13/09/1990","bloodGroup":"O+ve",
"listOfEmail":["dunston08#gmail.com","charles.gmail.com","ravi.gmail.com"],
"listOfURL":["www.google.com","www.gmail.com","www.facebook.com"],
"listOfFaxNo":[8888888888,1111111111,2222222222,3333333333],
"listOfOfficeNo":[9999999999,8888888888,7777777777,6666666666],
"listOfAddress":[{"streetName":"xxxxx","city":"yyyyy","zipCode":"5555555","state":"hhhhhhh"},
{"streetName":"xxxxx","city":"yyyyy","zipCode":"5555555","state":"hhhhhhh"}]
}
this is my json object i want to map it to three different classes
Class PersonDetail
{
firstName
lastName
jobTitle
dateOfBirth
bloodGroup
/* Getter Setter */ of the above attributes
}
class PersonContact extends PersonDetail
{
ArrayList<String> listOfEmail=new ArrayList<String>();
ArrayList<String> listOfURL=new ArrayList<String>();
ArrayList<String> listOfFaxNo=new ArrayList<String>();
ArrayList<String> listOfPhoneNo=new ArrayList<String>();
/* Getter Setter */ of the above attributes
}
class Address extends PersonContact
{
String streetName;
String city;
String zipcode;
String state;
/* Getter Setter */ of the above attributes
}
Not tested, but the you should be able to map your json to PersonContact using the following class definitions:
Class PersonDetail
{
protected String firstName;
protected String lastName;
protected String jobTitle;
protected String dateOfBirth;
protected String bloodGroup;
/* Getter Setter */ of the above attributes
}
class PersonContact extends PersonDetail
{
private ArrayList<String> listOfEmail;
private ArrayList<String> listOfURL;
private ArrayList<String> listOfFaxNo;
private ArrayList<String> listOfOfficeNo;
private List<Address> listOfAddress;
/* Getter Setter */ of the above attributes
}
class Address
{
private String streetName;
private String city;
private String zipcode;
private String state;
/* Getter Setter */ of the above attributes
}
Just use https://github.com/FasterXML/jackson-databind
The tutorial should enable you to map the same source to different java objects (classes)