2014年12月23日21:54:56 心情稍微好转
1、导入 jar 包
jackson-annotations-2.4.4.jar 下载地址
jackson-core-2.4.4.jar 下载地址
jackson-databind-2.4.4.jar 下载地址
2、使用的具体步骤
(1)、创建com.fasterxml.jackson.databind.ObjectMapper对象
(2)、调用ObjectMapper 的 wirteValueAsString 方法把java对象或集合转为JSON字符串
ObjectMapper objectMapper = new ObjectMapper();
String jsonstr = objectMapper.writeValueAsString(customer);
(3)注意:
①、JackSon根据getter来定位Json 对象的属性,而不是字段!
②、可以在类的getter 方法上添加注解:com.fasterxml.jackson.annotation.JsonIgnore 在转为 JSON对象时以忽略改属性
Customer.java
package com.gditc.beans;
import java.util.Arrays;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Customer {
private String name;
private String id;
public Customer(String name, String id) {
super();
this.name = name;
this.id = 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 String getCity() {
return "Guangzhou";
}
@JsonIgnore
public String getBirthday() {
return "1990-07-26";
}
public static void main(String[] args) throws JsonProcessingException {
// 1.导入 jar包
// 2.创建ObjectMapper对象
ObjectMapper objectMapper = new ObjectMapper();
// 3.调用mapper的writeValueAsString() 方法把一个对象转为一个JSON字符串
Customer customer = new Customer("AAAA", "1001");
String jsonstr = objectMapper.writeValueAsString(customer);
System.out.println(jsonstr);
// 4注意:JSON使用getter方法把一个对象转为一个JSON字符串
// 5.可以通过添加注解 com.fasterxml.jackson.annotation.JsonIgnore
// 忽略某个getter定义的属性
List<Customer> customers = Arrays.asList(customer, new Customer("BBB", "1002"));
jsonstr = objectMapper.writeValueAsString(customers);
System.out.println(jsonstr);
}
}
觉得挺可以的,分享给大家