Custom serialization in spring boot java.

AHMED M A
2 min readMar 13, 2021

Using Custom JSON serialization in spring boot java API, by using JoinView annotation with spring boot will customize our JSON response when you want to serialize your JSON response, @JsonView is the best approach is to limit your JSON response, In another hand to specify one or more views of properties of an object to be serialized or not.

How to use @jsonView?

  1. -import jsonView from java JSON library Jackson

import com.fasterxml.jackson.annotation.JsonView;

2. -JSON view should receive an argument @JsonView(BasicView.class)

3. Create class basic view Serializer, I called it class ViewSerialization in this project.

public class View {

}

4. We will call the instance of an object of class ViewSerialization we have been created View.Summary.class inside @jsonView annotation @jsonView(ViewSerialization.class). Then ViewSerialization.class will retrieve the instance of object ViewSerialization.

5. Then we will apply @JosnView annotation to each attribute we want to view it in JSON response like this.

@JsonView(ViewSerialization.class)

private String fullname ;

@JsonView(ViewSerialization.class)

private String email;

6. Also to show all of them you have to put up to

@OneToMany annotation.

@JsonView(ViewSerialization.class)

@OneToMany(mappedBy=”user”,cascade = CascadeType.ALL)

Without using step number 6 you will not be able to view appointments properties:

[

{

“userid”: 1,

“fullname”: “Ahmed Afandy”,

“email”: “ahmed.gmail.com”

},

{

“userid”: 2,

“fullname”: “Aylin Afandy”,

“email”: “aylin@gmail.com”

}

]

8- last step you have to include JsonView in your controller otherwise you will get an error, infinity json response .

@JsonView(ViewSerialization.class)

@GetMapping(“/users”)

9-after start the server you will get all user with his many associations.

[

{

“userid”: 1,

“fullname”: “Ahmed Afandy”,

“email”: “ahmed.gmail.com”,

“appointments”: [

{

“id”: 3,

“Description”: “appointment with Doctor”,

“type”: “health”,

“date”: “03/12/2021”,

“time”: “2:30pm”

},

{

“id”: 5,

“Description”: “DPS appointment”,

“type”: “Transportation”,

“date”: “03/02/2021”,

“time”: “7:31am”

}

]

}

]

*Another reason using costume serialization is to show the properties of the appointments that each user has it .because auto serialization will not show te properites ,it will just show link to the each appointment .

[

{

“userid”: 1,

“fullname”: “Ahmed Afandy”,

“email”: “ahmed.gmail.com”,

“appointments”: [

{ “_links”:{

“ self”:{

“href”:”http://localhost:8080/users/1/appointments"

}}

Conclusion

Serialization is an important process to simplify the JSON response, then use that response easily in the front-end process. When you have a complex relational database using custom serialization to limit the attributes of an object and joined objects, that make the process faster and decrease the load process.

--

--