Jackson's use and customize

springmvc when using annotations @ResponseBody return a POJO objects, which means Jackson will be done inside POJO into JSON work. 

public  class the Message { 
 
  Private String the userId; // User ID 
 
  Private String Message; // Message Entity 
 
  Private a Date timestamp; // time information, the MM-dd-YYYY HH: mm: SS 
 
  Private String Extra; // additional incidental information 
 
}

The final say converted to the following json format:
  
  If the developer needs the following requirements:
  . 1) Key json entity naming all lowercase of different words to "_" character connection.
  2) return time field, must meet. " yyyy-mM-dd HH: mm : ss " format
  . 3) omit the extra field
  shows that our ultimate goal is:

{"user_id":"1001","message":"message","timestamp":"2015-08-31 12:16:30"}

Settlement papers:
  •  Rename
  jackson processing rename the introduction of notes JsonProperty to achieve its configuration is valid for a single property.

@JsonProperty(value="user_id")
private String userId; // 用户id

Note: value property to the desired user name can be.
  Of course, there is another way annotation mode is JsonNaming , which is modified on the POJO class is used for all properties, unified naming convention.

@JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class)
public class Message {
  ...
}

Note:  PropertyNamingStrategy very nice to all the class attribute names are converted to lowercase, use '_' character between words (hump command method) to separate.
  From Strategy class definition, need to implement the following abstract class:

public abstract class PropertyNamingStrategy implements Serializable {
  public abstract static class PropertyNamingStrategyBase extends PropertyNamingStrategy {
    public abstract String translate(String var1);
  }
}

  •  field visibility
  filter certain field properties, jackson introduced notes JsonIgnore . Which entered into force for a single property.

@JsonIgnore
 Private String Extra; // additional accompanying information

There is another way, is to use JsonIgnoreProperties, it modifies POJO class specifies a set of fields to be ignored.

// *) {} dictionary is the property name in the list 
@JsonIgnoreProperties ({ "Extra", "extra1", "extra2" })
 public  class the Message { 
  ... 
}

  •  custom serialization / deserialization
  jackson using @JsonSerialize and @JsonDeserialize to implement custom serialization achieved / deserialization As before the time field as an example.

Defines the time sequence of the implementation class.

public class Message {
 
  @JsonSerialize(using=DemoDateSerializer.class)
  @JsonDeserialize(using=DemoDateDeserializer.class)
  private Date timestamp; // 时间信息, yyyy-MM-dd HH:mm:ss
 
}
 
// *) JSON的序列化类
class DemoDateSerializer extends JsonSerializer<Date> {
  @Override
  public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    jgen.writeString(dateFormat.format(value));
  }
}
 
// *) JSON的反序列化类
class DemoDateDeserializer extends JsonDeserializer<Date> {
  @Override
  public Date deserialize(JsonParser jp, DeserializationContext dctx) throws IOException, JsonProcessingException {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
      return dateFormat.parse(jp.getValueAsString());
    } catch (ParseException e) {
      e.printStackTrace();
    } finally {
    }
    return null;
  }
}

In addition to the conventional time format conversion, but also regular extraction functions. Custom serialization and deserialization, so Jackson more powerful. UDF function like the hive.

The final class is defined by the following:

public  class the Message { 
 
  @JsonProperty (value = "user_id" )
  Private String the userId; // User ID 
 
  Private String Message; // Message Entity 
 
  @JsonSerialize (the using . DemoDateSerializer = class ) 
  @JsonDeserialize (the using . DemoDateDeserializer = class )
  Private a Date timestamp ; // time information, the mM-dd-YYYY HH: mm: SS 
 
  @JsonIgnore 
  Private String extra; // additional incidental information 
 
}

@DateTimeFormat and @JsonFormat comment

Define a pojo, it has a property of type java.util.Date date.

import java.util.Date;

public class DateVo {
    private Date date;

    public void setDate(Date date){
        this.date = date;
    }
    public Date getDate(){
        return date;
    }
}

The definition of a Controller

@RestController
@RequestMapping("/date/")
public class DateController {

    @RequestMapping("test")
    public DateVo getDate(DateVo vo){
        System.out.println("date1:"+vo.getDate());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(vo.getDate());
        System.out.println("date2:"+date);

        DateVo vo2 = new DateVo();
        vo2.setDate(new Date());
        return vo2;
    }
}

Access / date / test, and pass parameters: 2018-08-02 22:05:55

And can not find a successful visit, you will throw an exception:

2 into the reference format

In this case, you can use formatting parameters @DateTimeFormat annotation of Spring, to solve the problem.

public class DateVo {
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date date;

    public void setDate(Date date){
        this.date = date;
    }
    public Date getDate(){
        return date;
    }
}

Then as above access / date / test, and pass parameters: 2018-08-02 22:05:55, will be printed on the console:

date1: Thu Aug 02 22:05:55 CST 2018

date2:2018-08-02 22:05:55

It can be seen, after adding @DateTimeFormat annotation parameters may be received, but the date and time format still needs its own and then manually convert it.

Because @DateTimeFormat annotation pattern attribute specifies a date format is not time to convert to date format, and this format is specified corresponding to the parameters passed, if the annotated as:

@DateTimeFormat (pattern = "yyyy / MM / dd HH: mm: ss") is passed in this parameter should be: 2018/08/02 22:05:55

3. the reference format

In the above example, the interface call returns a result:

"date": "2018-08-01T14:25:31.296+0000"

This format is not what we want, then how will it be formatted? Then you need to use the @JsonFormat jackson comment.

public class DateVo {
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @JsonFormat(
            pattern = "yyyy-MM-dd HH:mm:ss"
    )
    private Date date;

    public void setDate(Date date){
        this.date = date;
    }
    public Date getDate(){
        return date;
    }
}

Continued access / date / test, and pass parameters: 2018-08-02 22:05:55, we can see the results returned interface is:

"date": "2018-08-01 14:32:57"

Although the time in the correct format, but in fact the current time is "2018-08-01 22:32:57", as early as 8 hours. Because, Jackson during serialization time is formatted in accordance with international standard GMT time, default time zone in the country using the CST time zone, a difference of 8 hours.

So, @ JsonFormat notes also coupled with a property:

@JsonFormat(
    pattern = "yyyy-MM-dd HH:mm:ss",
    timezone = "GMT+8"
)
private Date date;

In this way, the result is correct.

@JsonInclude (JsonInclude.Include.NON_NULL) label removal problems null data json

@JsonInclude (JsonInclude.Include.NON_NULL) marker sequence is json jackson package provides methods have been integrated in Springboot2.0, this method may be arranged in the intended numerical value corresponding to the processing entity is serialized json,

Attribute on the tag, if the property is not NULL sequence of participation 
if placed in the upper class, that all the properties of this class of functions 
Include.Include.ALWAYS default 
Include.NON_DEFAULT not attribute to the default value of the sequence 
Include .NON_EMPTY property is empty ( "") is NULL or not serialized 
Include.NON_NULL serialization attribute is not NULL 

 

Guess you like

Origin www.cnblogs.com/deityjian/p/11080138.html