-
Notifications
You must be signed in to change notification settings - Fork 3
Getting started
Quirino Zagarese edited this page Apr 19, 2015
·
3 revisions
Here are few scenarios where Hyaline can help you. Examples use Jackson, but you can use whatever you want.
Your domain classes look like this:
public class Person {
private String firstName;
private String lastName;
private Address address;
//getters and setters
}
public class Address {
private String street;
private int number;
private String zipcode;
private String city;
private String country;
//getters and setters
@Override
public String toString() {
return number + " " + street + ", " + city + " " + zipcode + ", " + country;
}
}
Jackson default serialization produces something like this:
{
"firstName" : "John",
"lastName" : "Lennon",
"address" : {
"street" : "Abbey Road",
"number" : 123,
"zipcode" : "NW8 9AX",
"city" : "London",
"country" : "UK"
}
}
Person person = methodReturningInitializedPerson();
Person dto = Hyaline.dtoFromScratch(person, new DTO() {
@JsonIgnore
private Address address;
});
Hyaline detects that field address
matches a field in class Person
, so it injects the @JsonIgnore
configuration on that field.
Note that your dto
will be assignable to your entity type, so if your method returned a Person
,
it can still return such type.
Here is the output:
{
"firstName" : "John",
"lastName" : "Lennon"
}
Person person = methodReturningInitializedPerson();
Person dto = Hyaline.dtoFromScratch(person, new DTO() {
@JsonIgnore
private Address address;
@JsonProperty("name")
private String firstName;
@JsonProperty("surname")
private String lastName;
});
Output:
{
"name" : "John",
"surname" : "Lennon"
}
final Person person = methodReturningInitializedPerson();
Person dto = Hyaline.dtoFromScratch(person, new DTO() {
@JsonIgnore
private Address address;
@JsonProperty("address")
private String stringAddress = person.getAddress().toString();
@JsonProperty("name")
private String firstName;
@JsonProperty("surname")
private String lastName;
});
This is what I get:
{
"name" : "John",
"surname" : "Lennon",
"address" : "123 Abbey Road, London NW8 9AX, UK"
}
4. Well, I need to give a specific order to json properties and Jackson allows me to do it only at class level.
This is less elegant because of some limitations of the author and the Java compiler (suggestions are very welcome!!!). Here is how to do it:
final Person person = methodReturningInitializedPerson();
Person dto = Hyaline.dtoFromScratch(person, new DTO() {
private MyTemplate t = new MyTemplate();
@JsonPropertyOrder(alphabetic = true)
class MyTemplate {
@JsonIgnore
private Address address;
@JsonProperty("address")
private String fullAddress = person.getAddress().toString();
@JsonProperty("name")
private String firstName;
@JsonProperty("surname")
private String lastName;
}
});
Tah daaaaah:
{
"address" : "123 Abbey Road, London NW8 9AX, UK",
"name" : "John",
"surname" : "Lennon"
}