Java with Jackson and JSON

Java with Jackson and JSON

Introduction:

every developer knows about JSON, and many developers use Json format with API requests or responses.


So what is?JSON:

JSON is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute-value pairs and arrays.
— Wikipedia

In this article, I will write a java code to represent many scenarios and how we can handle them with JSON.

I will use?Lomobok?library in this project, it provides us with more readability for our code. and save effort and time.

So Let's go to see it.




In this first step, we need to create a new Java project with Maven as a package dependency.


Inside our?pom.xml?the file we need to add the following dependency, to install it from the maven repository and activated it in our project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.5</version>
</dependency>        



Now we will use?ObjectMapper?, it provides us with much fixability and saves our effort and time, to convert from JSON to Java class or vice versa.

How we can use it in Java projects?

To use?ObjectMapper?we will define it as an object like the following, and I will write a configuration to void the unknown property problem.

ObjectMapper mapper = new Mapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);        

In some cases, we need to use the object mapper.

We have many cases, that need to use ObjectMapper. but I will mention famous cases. And how we can apply it.

First, we have a Class called Student like the following, and we will take this class as a case study to understand Utilize?jackson?and?ObjectMapper:

@Data
@AllArgsConstrauctor
@NoArgsConstrauctor
@Builder
public class Student{
  private Long id;
  private String name;
  private Integer age;
  private String gender
}        

  • Convert JSON String to JSON tree


If we have the following String to represent JSON as a String, and we need to convert it to a JSON tree to use with business needs,?ObjectMapper?can handle it, look at the following Sneppit.

String studentJsonString = "{\"name\":\"salitha\"
+ ,\"first_name\":\"salitha\",
+ \"last_name\":\"chathuranga\",
+ \"age\":28,
+ \"skills\":[\"Java\"]}";
JsonNode studentNode = mapper.readTree(studentJsonString);        

  • Convert JSON String to Object


If we have the following JSON String and we need to convert it to?Student Object.?The?ObjectMapper?can handle logic.

String studentJsonString = "{\"name\":\"salitha\"
+ ,\"first_name\":\"salitha\",
+ \"last_name\":\"chathuranga\",
+ \"age\":28,
+ \"skills\":[\"Java\"]}";
Student student= mapper.convertValue(studentJsonString, Student.class);
        

  • Convert Object to JSON


If we need to convert Student Object to a JSON tree,?ObjectMapper?can handle this logic.

Student student = Student
.builder()
.id(1L)
.name("abdalrhman")
.age(18)
.gender("male)
.build();

JsonNode node = mapper.valueToTree(student);        

  • Convert JSON to List of Objects


Now if the business Logic required converting?JSON has a List?to a List of Objects,?ObjectMapper?can handle this logic.

String studentJsonString = "[{\"name\":\"salitha\"
+ ,\"first_name\":\"salitha\",
+ \"last_name\":\"chathuranga\",
+ \"age\":28,
+ \"skills\":[\"Java\"]}]";
Student student= mapper.convertValue(
  studentJsonString,
  new TypeReference<List<Student>>(){}
);        

  • Convert List of Objects to JSON


Also, we can convert the List of Objects to a?JSON?tree By?ObjectMapper?.

List<Student> students = Collections
        .singletonList(Student
                  .builder()
                  .id(1L)
                  .name("abdalrhman")
                  .age(18)
                  .gender("male)
                   .build());

JsonNode node = mapper.valueToTree(students);        



Jackson Annotations:

Jackson provides us with many notifications to handle and control the class variable and mapping between JSON and object.

So I will use the above class with Jackson Annotations to explain the common annotations.

So The following class represents our study case

@Data
@AllArgsConstrauctor
@NoArgsConstrauctor
@Builder
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Student{
  private Long id;
  
  @JsonProperty("user_name")
  private String name;
  private Integer age;
  private String gender
  @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
  private List<Skill> skills;
}        

  • JsonNaming


This is used for naming conventions in Java — JSON objects. Let’s take one convention. I need to create properties in a JSON object(after serialization), which are having property names in “SNAKE CASE”. I need this for all the properties I define. Then, it’s simple! Put this on top of the class definition.

  • JsonProperty


JsonProperty is used?when we need to define a property that is different from the property name when it is converted into JSON. Here our student JSON has the property?“user_name”. But we define the property as a?“name”?in POJO.

  • JsonInclude


When we use the?Builder?pattern in Lombok, we can define objects however we want. That means we can omit some properties and keep them as NULL. If I need to create a student who has NO SKILLS, it’s fine. But when I converted it to JSON,?I do not want to see NULL properties in JSON. This is the place we use this annotation! Put this on top of the class definition.

  • JsonFormat


The?JSON?format is used if we are unexpectedly requesting format for fields, for example, if the user sends Skills filed as a string, that is wrong because the skills need a List of Strings.

for example:

{“id”:1,”name”:”abdalrhman”,”age”:18,”gender”:”male” ,”skills”:”Java”}


This annotation will handle the response like the following

Student(id = 1, name = "abdlarhman", age = 28, skills = ["Java"])
        



Conclusion:

The Jackson library gives the developer many features to work with?JSON,

and help by saving our effort and time.

Also, we need to know how we can use?JSON?because many projects and systems use it.

By the way, Java provides us?ObjectMapper?to help the developer work with JSON.

Steven Shi

Look for influencers (Bloggers)of developer | Marketing Manger | Influencer Marketing @Scudata

1 年

Hi , I'm Steven it's nice to meet you. I take care of partnerships at esProc, focusing on backend developers 、full-stack developers etc. I wonder whether you typically work with brands like us on sponsored tweets or similar content. We have built esProc SPL which is a scripting language for data processing with well-designed library functions. You can know more about it https://c.raqsoft.com/article/1642764366712 https://c.raqsoft.com/article/1649920231365 and take a look at the GitHub repository https://github.com/SPLWare/esProc We're l looking for Twitter influencers and technical writers like yourself whom we could collaborate with on the promotion of our product. Paid of course. The form of promotion is generally that I provide you with technical articles, and you are responsible for publishing them on your technical community platform (including Twitter); Most of the articles provided are in this link: https://c.raqsoft.com/domain/Blog If this is something that could interest you, please let me know. We can also move to email if you want, mine is [email protected]

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了