json入门
json:是一种轻量级的数据交互格式。
jackson可以实现java对象与json的转换,并且它与Spring的整合较好
jackson快速入门:
1.将jackson-databind-2.8.1.jar jackson-core-2.8.1.jar jackson-annotations-2.8.0.jar导入lib包中
2.建立一个javabean
3.创建一个对象
4.创建一个ObjectMapper对象
5.System.out.println(mapper.writeValueAsString(s1));即可以json数据格式打印到控制台
package com.imooc.page.model; import java.io.Serializable; import jdk.nashorn.internal.ir.annotations.Ignore; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreType; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data//@Getter和@Setter:为属性创建getter和setter //使用lombok@EqualsAndHashCode:实现equals()方法和hashCode()方法 //@ToString:实现toString()方法 //@Data:上述3个annotation的和,会创建getter setter equals hashCode和toString @NoArgsConstructor//实现无参构造方法 @AllArgsConstructor//实现带所有字段的构造方法 @JsonIgnoreProperties({"stuName","address"})//输出json数据时不输出stuName,address public class Student implements Serializable { /** * */ private static final long serialVersionUID = -7476381137287496245L; //@JsonProperty("ID")//输出json格式的别名 private int id;//学生记录 private String stuName;//学生姓名 private int age;//学生年龄 private int gender;//学生的性别 private String address;//学生地址 }
package com.imooc.page.model; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JackSon { @Test public void printJackSon() throws JsonProcessingException{ Student s1 = new Student(1,"huxuebing",20,1,"hunan"); ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writeValueAsString(s1)); } }
{"id":1,"age":20,"gender":1}