常用Json框架(Jackson)
Jackson处理相关字段
-
指定字段不返回,比如密码:@JsonIgnore
-
指定日期格式:@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")
-
空字段不返回:@JsonInclude(Include.NON_NUll)
-
指定别名:@JsonProperty
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int age; private String pwd; private String phone; private Date createTime; }
@RestController public class SampleController { @GetMapping("/testjson") public Object testjson(){ return new User(111, "abc123", "10001000", new Date()); } }
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class XdclassSpringbootApplication { public static void main(String[] args) { SpringApplication.run(XdclassSpringbootApplication.class, args); } }
测试结果
{ "age": 111, "pwd": "abc123", "phone": "10001000", "createTime": "2019-07-24T12:50:41.798+0000" }
改变User的属性,使用Json的注解。
返回的json可能为空串“” 或者 0 或者 [], 但尽量不要null。给 phone 添加 @JsonInclude(JsonInclude.Include.NON_NULL) 注解。
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int age; @JsonIgnore private String pwd; @JsonProperty("account") @JsonInclude(JsonInclude.Include.NON_NULL) private String phone; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8") private Date createTime; }
{ "age": 111, "createTime": "2019-07-24 21:02:56", "account": "10001000" }
{ "age": 111, "createTime": "2019-07-24 21:11:38" }
{ "age": 111, "createTime": "2019-07-24 21:15:07", "account": "" }