Jackson-将对象转为Json字符串
1、引入jackson依赖
<properties> <jackson.version>1.9.13</jackson.version> </properties> <dependencies> <!-- json和bean之间相互转换 --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>${jackson.version}</version> </dependency> </dependencies>
2、具体使用步骤
①、创建org.codehaus.jackson.map,ObjectMapper对象
②、调用ObjectMapper的writerValueAsString 方法把Java对象或集合转为JSON字符串
3、Demo
import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.util.Arrays; import java.util.List; public class Customer { private String name; private String id; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Customer(String name, String id) { super(); this.name = name; this.id = id; } public String getCity(){ return "beijing"; } @JsonIgnore public String getBirthday(){ return "1980-12-12"; } public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException { //1.导入jar包 //2.创建objectmappter对象 ObjectMapper mapper=new ObjectMapper(); //3.调用mapper的writeValueAsString()方法把一个对象或集合转为json字符串 Customer customer=new Customer("aaa", "333"); String jsonStr=mapper.writeValueAsString(customer); System.out.println(jsonStr); //4.注意:jackson使用getter方法来定位json对象的属性 //5.可以通过添加注解JsonIgnore忽略某一个getter定义的属性 List<Customer> customers=Arrays.asList(customer,new Customer("bb", "213")); jsonStr=mapper.writeValueAsString(customers); System.out.println(jsonStr); } }
控制台结果
{"name":"aaa","id":"333","city":"beijing"}
[{"name":"aaa","id":"333","city":"beijing"},{"name":"bb","id":"213","city":"beijing"}]
4、注意点
①、JackSon 根据getter 来定位Json 对象的属性,而不是字段
②、可以在类的getter方法上添加注解:
org.codehaus.jackson.annotate.JsonIgnore
在转为Json对象是以忽略该属性