jackson的maven依赖java
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
因此引入这一个依赖就能够了json
@JsonProperty 此注解用于属性上,做用是把该属性的名称序列化为另一个名称,如把trueName属性序列化为name,@JsonProperty(value="name")。app
import com.fasterxml.jackson.annotation.JsonProperty; public class Student { @JsonProperty(value = "real_name") private String realName; public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } @Override public String toString() { return "Student{" + "realName='" + realName + '\'' + '}'; } }
测试maven
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class Main { public static void main(String[] args) throws JsonProcessingException { Student student = new Student(); student.setRealName("zhangsan"); System.out.println(new ObjectMapper().writeValueAsString(student)); } }
结果ide
{"real_name":"zhangsan"}
这里须要注意的是将对象转换成json字符串使用的方法是fasterxml.jackson提供的!!工具
若是使用fastjson呢?测试
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.28</version> </dependency>
import com.alibaba.fastjson.JSON; public class Main { public static void main(String[] args) { Student student = new Student(); student.setRealName("zhangsan"); System.out.println(JSON.toJSONString(student)); } }
结果this
{"realName":"zhangsan"}
能够看到,@JsonProperty(value = "real_name")没有生效,为啥?spa
由于fastjson不认识@JsonProperty注解呀!因此要使用jackson本身的序列化工具方法!code
--------------------------
@JsonProperty不单单是在序列化的时候有用,反序列化的时候也有用,好比有些接口返回的是json字符串,命名又不是标准的驼峰形式,在映射成对象的时候,将类的属性上加上@JsonProperty注解,里面写上返回的json串对应的名字
import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { String jsonStr = "{\"real_name\":\"zhangsan\"}"; Student student = new ObjectMapper().readValue(jsonStr.getBytes(), Student.class); System.out.println(student); } }
结果:
Student{realName='zhangsan'}