• Json object operation
  • Serialization operation
  • deserialization
  • Deserialization of date types
  • Custom deserialization
  • Enumeration type deserialization

background

Recently, ali’s Fastjson frequently exposed security vulnerabilities, in order to avoid the trouble of the subsequent upgrade online, I decided to abandon Fastjson and use Jackson instead of fastjson in the existing project. Since many of the writing methods are somewhat different, I would like to make a note of these changes here.

Common operations

First, the related POM is introduced


    <properties>
        <jackson.version>2.11.0</jackson.version>
    </properties>
    <dependencies>
 <dependency>  <groupId>com.fasterxml.jackson.core</groupId>  <artifactId>jackson-core</artifactId>  <version>${jackson.version}</version>  </dependency>  <dependency>  <groupId>com.fasterxml.jackson.core</groupId>  <artifactId>jackson-databind</artifactId>  <version>${jackson.version}</version>  </dependency>  <dependency>  <groupId>com.fasterxml.jackson.core</groupId>  <artifactId>jackson-annotations</artifactId>  <version>${jackson.version}</version>  </dependency>  </dependencies>  Copy the code

Json object operation

When we need a JSON object and array, we can use the following method to construct ObjectNode and ArrayNode, similar to JSONObject and JSONArray in FastJSON.


 @Test
 public void testJsonObject(a){
  ObjectMapper mapper = new ObjectMapper();
  ObjectNode json = mapper.createObjectNode();
 json.put("name"."Tom");  json.put("age".1);  System.out.println(json);   ArrayNode jsonNodes = mapper.createArrayNode();  jsonNodes.add(json);  System.out.println(jsonNodes);  }  Copy the code

Serialization operation

Serialization is converting a Java object to JSON. The syntax is simple:


 @Test
 public void testSerialize(a) throws JsonProcessingException{
  User user = new User();
  user.setAge(1);
 user.setName("zhangsan");  user.setGender(GENDER.MALE);  user.setBirthday(new Date());  ObjectMapper mapper = new ObjectMapper();  String s = mapper.writeValueAsString(user);  System.out.println(s);  }   Copy the code

There is no doubt about the plain String and int types, but we are dealing with two special types here, one is Date and one is enumeration. Date types We use the @jsonFormat annotation to format the date type and control the format of the output.


@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private Date birthday;

Copy the code

Enumeration type, which we control to output by annotating @jsonValue.


      @JsonValue
  public String getName(a){
   return name;
  }
 Copy the code

deserialization

Deserialization is converting JSON to A Java object, syntax is as follows:


 @Test
 public void testDeSerialize(a) throws JsonProcessingException{
  String json = "{\"name\":\"zhangsan\",\"age\":10}";
  ObjectMapper mapper = new ObjectMapper();
 User user = mapper.readValue(json, User.class);  System.out.println(user);  }   Copy the code

Deserialization of date types

For the Date type, the following formats are supported:

  • A timestamp of type long
  • The @jsonFormat annotation specifies the type format: YYYY-MM-DD HH: MM: SS

 @Test
 public void testDeSerializeDate(a) throws JsonProcessingException{
  String json = "{\"name\":\"zhangsan\",\"age\":10,\"birthday\":1592800446397}";
  ObjectMapper mapper = new ObjectMapper();
 User user = mapper.readValue(json, User.class);  System.out.println(user);   String json1 = "{\"name\":\"zhangsan\",\"age\":10,\"birthday\":\"2020-01-01 12:13:14\"}";  User user1 = mapper.readValue(json1, User.class);  System.out.println(user1);   }  Copy the code

Custom deserialization

Sometimes the deserialization method provided by the system does not meet our needs. We can customize some methods to meet our personalized needs. Let’s take a date as an example to talk about how to customize deserialization.

First we specify the deserialize class by annotating @jsondeserialize on the corresponding field

@JsonDeserialize(using = CustomDeserializerDate.class)
    private Date birthday_custom;

Copy the code

The custom serialization class inherits the abstract class StdDeserializer. In addition, we need to add a no-argument constructor, otherwise we will get an error. In the deserialize method we implement deserialize logic.



   public static class CustomDeserializerDate extends StdDeserializer<Date>{

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  protected CustomDeserializerDate(Class
              vc){  super(vc);  }   // A no-argument constructor is required, otherwise an error is reported  public CustomDeserializerDate(a){  this(null);  }   @Override  public Date deserialize(  JsonParser p,  DeserializationContext ctxt) throws IOException{  String date = p.getText();  try {  return sdf.parse(date);  } catch (ParseException e){  e.printStackTrace();  }  return null;  }  }  Copy the code

Enumeration type deserialization

Finally, deserialization of enumerated types

As shown in the code below, we handle enumeration deserialization by annotating @JsonCreator, which takes a parameter of type int, the value of the enumeration, and returns the enumeration type GENDER. If not found, null is returned.


 public static enum GENDER{
  MALE("Male".1), FEMALE("Female".0);
  private String name;
  private int value;
  @JsonCreator  public static GENDER getGenderById(int value){  for (GENDER c: GENDER.values()){  if (c.getValue() == value){  return c;  }  }  return null;  }  . } Copy the code

The complete code refer to: https://github.com/zhangjun0x01/bigdata-examples/blob/master/java/src/main/java/json/JacksonTest.java

Welcome to follow my official account, [Big data technology and Application combat], for more exciting content