深入学习java笔记-5.SpringBoot2.1之lombok,jackson

pom.xml
        
            org.projectlombok
            lombok
        
User.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class User {

    private Integer id;

    private String username;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Integer age;

    @JsonProperty("account")
    private String phone;

    @JsonIgnore
    private String email;

    @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", locale = "zh", timezone = "GMT+8")
    private Date createTime;
}

@JsonInclude(JsonInclude.Include.NON_NULL) 指定该字段不能为空
@JsonProperty("account") 将该字段属性名(phone)换成account
@JsonIgnore 返回的json数据中去掉该属性和值
@JsonFormat 返回json数据的值格式化
@Data 其中包含了很多@Override的方法,例如@Setter,@Getter,@ToString,@HashCode等
@AllArgsConstructor 全参构造器
@NoArgsConstructor 无参构造器
@Builder 建造者模式 与那种链式编程相似

public class Person{
    Integer id;
    String name;
    public static Person Builder(){
        return this;
    }
    public static Person Id(Integer id){
        this.setId(id);
        return this;
    }
    public static Person Name(String name){
        this.setName(name);
        return this;
    }
}
JsonUtils.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.Assert;

import java.io.IOException;

public class JsonUtils {

    private static ObjectMapper objectMapper = new ObjectMapper();

    public static  String obj2String(T obj) {
        Assert.notNull(obj, "obj must not be null");
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static  T string2Obj(String str, Class clazz) {
        Assert.notNull(str, "str must not be null");
        Assert.notNull(clazz, "clazz must not be null");
        try {
            return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

com.fasterxml.jackson.databind.ObjectMapper
objectMapper.writeValueAsString 对象转字符串
objectMapper.readValue 字符串转对象
后续springboot集成redis时会有用到。

你可能感兴趣的:(深入学习java笔记-5.SpringBoot2.1之lombok,jackson)