使用jackson工具类把对象或集合转为JSON格式
jackson使用方法:
1、加入jar包:
jackson-annotations-2.2.2.jar
jackson-core-2.2.2.jar
jackson-databind-2.2.2.jar
2、具体的使用步骤:
1)、创建org.codehaus.jackson,map.ObjectMapper 对象
2)、调用ObjectMapper 的 writeValueAsString 方法把Java 对象或集合转为JSON字符串
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writerValueAsString(String str);
3、注意:
1)、Jackson 根据getter 来定位Json 对象的属性,而不是字段!
2)、可以在类的 getter 方法上添加注解:org.codehaus.jackson.annotate.JsonIgnore . 转为Json对象时已忽略该属性!
测试代码如下:
package com.lym.ajax.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; /** * jackson测试类 * @author liuyanmin * 2015-1-20 上午11:23:55 */ public class ShopCart { private String bookName; private int price=0; private int number=0; public ShopCart(String bookName, int price, int number) { super(); this.bookName = bookName; this.price = price; this.number = number; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } @JsonIgnore public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public static void main(String args[]){ ObjectMapper mapper = new ObjectMapper(); ShopCart sc = new ShopCart("JavaEE",100,1); List<ShopCart> list = Arrays.asList(sc,new ShopCart("Oracle",200,2)); try { String result = mapper.writeValueAsString(sc); String resList = mapper.writeValueAsString(list); System.out.println(result); System.out.println(resList); } catch (JsonProcessingException e) { e.printStackTrace(); } } }