Json字符串和Java对象转换利器——Jackson

Maven配置:

	com.fasterxml.jackson.core
	jackson-databind
	2.1.3
实体类GetOrdersResponse:
package org.jackson.jsontest.po;

import java.util.List;
 
/**
 * Generated by FreeMarker
 *
 */
public class GetOrdersResponse  
{
    /********** attribute ***********/
    private String timestamp;

    private String ack;

    private String version;

    private String build;
    
    private PaginationResult paginationResult;

    private List orderArray;

  
    /********** get/set ***********/
    public String getTimestamp() {
        return timestamp;
    }
 
    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public String getAck() {
        return ack;
    }
 
    public void setAck(String ack) {
        this.ack = ack;
    }

    public String getVersion() {
        return version;
    }
 
    public void setVersion(String version) {
        this.version = version;
    }

    public String getBuild() {
        return build;
    }
 
    public void setBuild(String build) {
        this.build = build;
    }

	public List getOrderArray() {
		return orderArray;
	}

	public void setOrderArray(List orderArray) {
		this.orderArray = orderArray;
	}
	
	public PaginationResult getPaginationResult() {
		return paginationResult;
	}

	public void setPaginationResult(PaginationResult paginationResult) {
		this.paginationResult = paginationResult;
	}

	@Override
	public String toString() {
		return "GetOrdersResponse [ack=" + ack + ", build=" + build
				+ ", orderArray=" + orderArray + ", paginationResult="
				+ paginationResult + ", timestamp=" + timestamp + ", version="
				+ version + "]";
	}

}

实体类Order:

package org.jackson.jsontest.po;

import org.jackson.jsontest.po.order.CheckoutStatus;
 
/**
 * Generated by FreeMarker
 *
 */
public class Order  
{
    /********** attribute ***********/
    private String orderID;

    private CheckoutStatus checkoutStatus;

    private String buyerUserID;

  
    /********** get/set ***********/
    public String getOrderID() {
        return orderID;
    }
 
    public void setOrderID(String orderID) {
        this.orderID = orderID;
    }

    
    public CheckoutStatus getCheckoutStatus() {
        return checkoutStatus;
    }
 
    public void setCheckoutStatus(CheckoutStatus checkoutStatus) {
        this.checkoutStatus = checkoutStatus;
    }

    public String getBuyerUserID() {
        return buyerUserID;
    }
 
    public void setBuyerUserID(String buyerUserID) {
        this.buyerUserID = buyerUserID;
    }

	@Override
	public String toString() {
		return "Order [buyerUserID=" + buyerUserID + ", checkoutStatus="
				+ checkoutStatus + ", orderID=" + orderID + "]";
	}
  
}
实体类PaginationResult:
package org.jackson.jsontest.po;
 
/**
 * Generated by FreeMarker
 *
 */
public class PaginationResult  
{
    /********** attribute ***********/
    private String totalNumberOfEntries;

    private String totalNumberOfPages;

  
    /********** get/set ***********/
    public String getTotalNumberOfEntries() {
        return totalNumberOfEntries;
    }
 
    public void setTotalNumberOfEntries(String totalNumberOfEntries) {
        this.totalNumberOfEntries = totalNumberOfEntries;
    }

    public String getTotalNumberOfPages() {
        return totalNumberOfPages;
    }
 
    public void setTotalNumberOfPages(String totalNumberOfPages) {
        this.totalNumberOfPages = totalNumberOfPages;
    }

	@Override
	public String toString() {
		return "PaginationResult [totalNumberOfEntries=" + totalNumberOfEntries
				+ ", totalNumberOfPages=" + totalNumberOfPages + "]";
	}
  
}
实体类CheckoutStatus:
package org.jackson.jsontest.po.order;
 
/**
 * Generated by FreeMarker
 *
 */
public class CheckoutStatus  
{
    /********** attribute ***********/
    private String eBayPaymentStatus;

    private String lastModifiedTime;

    private String status;

  
    /********** get/set ***********/
    public String getEBayPaymentStatus() {
        return eBayPaymentStatus;
    }
 
    public void setEBayPaymentStatus(String eBayPaymentStatus) {
        this.eBayPaymentStatus = eBayPaymentStatus;
    }

    public String getLastModifiedTime() {
        return lastModifiedTime;
    }
 
    public void setLastModifiedTime(String lastModifiedTime) {
        this.lastModifiedTime = lastModifiedTime;
    }

    public String getStatus() {
        return status;
    }
 
    public void setStatus(String status) {
        this.status = status;
    }

	@Override
	public String toString() {
		return "CheckoutStatus [eBayPaymentStatus=" + eBayPaymentStatus
				+ ", lastModifiedTime=" + lastModifiedTime + ", status="
				+ status + "]";
	}

}
工具类JackSon:
package org.jackson.jsontest;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JackSon {

	/**
	 * Json字符串转对象
	 * @param 
	 * @param jsonStr
	 * @param clazz
	 * @return
	 * @throws Exception
	 */
	public  T jsonStrToBean(String jsonStr, Class clazz) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.readValue(jsonStr, clazz);
	}

	/**
	 * 对象转Json字符串
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	public String beanToJsonStr(Object bean) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(bean);
	}
}
测试类JackSonTest:
package org.jackson.jsontest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jackson.jsontest.po.GetOrdersResponse;
import org.jackson.jsontest.po.Order;
import org.jackson.jsontest.po.PaginationResult;
import org.jackson.jsontest.po.order.CheckoutStatus;
import org.junit.Before;
import org.junit.Test;

public class JackSonTest {
	JackSon jackSon;
	
	static GetOrdersResponse ordersResponse;
	
	static String jsonStr;
	
	@Before
	public void before(){
		jackSon	= new JackSon();
	}
	
	static {
		ordersResponse = new GetOrdersResponse();
		ordersResponse.setTimestamp("2007-12-10T16:12:55.184Z");
		ordersResponse.setAck("Success");
		ordersResponse.setBuild("e539_core_Bundled_5642307_R1");
		ordersResponse.setVersion("539");
		List orders = new ArrayList();
		for (int i = 0; i < 3; i++) {
			Order order = new Order();
			order.setOrderID("OrderId_" + i);
			order.setBuyerUserID("BuyerUserId_" + i);
			
			CheckoutStatus checkoutStatus = new CheckoutStatus();
			checkoutStatus.setEBayPaymentStatus("EBayPaymentStatus_" + i);
			checkoutStatus.setLastModifiedTime("LastModifiedTime_" + i);
			checkoutStatus.setStatus("Status_" + i);
			order.setCheckoutStatus(checkoutStatus);
			
			orders.add(order);
		}
		ordersResponse.setOrderArray(orders);
		PaginationResult paginationResult = new PaginationResult();
		paginationResult.setTotalNumberOfEntries("10");
		paginationResult.setTotalNumberOfPages("5");
		ordersResponse.setPaginationResult(paginationResult);
	}
	
	@Test
	public void testBeanToJsonStr() {
		try {
			jsonStr = jackSon.beanToJsonStr(ordersResponse);
			System.out.println(jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testJsonStrToBean() {
		try {
			GetOrdersResponse ordersResponse = jackSon.jsonStrToBean(jsonStr, GetOrdersResponse.class);
			System.out.println(ordersResponse);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
结果:
-----------Java对象转Json字符串结果------------
{"timestamp":"2007-12-10T16:12:55.184Z","ack":"Success","version":"539","build":"e539_core_Bundled_5642307_R1","paginationResult":{"totalNumberOfEntries":"10","totalNumberOfPages":"5"},"orderArray":[{"orderID":"OrderId_0","checkoutStatus":{"lastModifiedTime":"LastModifiedTime_0","status":"Status_0","ebayPaymentStatus":"EBayPaymentStatus_0"},"buyerUserID":"BuyerUserId_0"},{"orderID":"OrderId_1","checkoutStatus":{"lastModifiedTime":"LastModifiedTime_1","status":"Status_1","ebayPaymentStatus":"EBayPaymentStatus_1"},"buyerUserID":"BuyerUserId_1"},{"orderID":"OrderId_2","checkoutStatus":{"lastModifiedTime":"LastModifiedTime_2","status":"Status_2","ebayPaymentStatus":"EBayPaymentStatus_2"},"buyerUserID":"BuyerUserId_2"}]}
-----------Json字符串转Java对象结果------------
GetOrdersResponse [ack=Success, build=e539_core_Bundled_5642307_R1, orderArray=[Order [buyerUserID=BuyerUserId_0, checkoutStatus=CheckoutStatus [eBayPaymentStatus=EBayPaymentStatus_0, lastModifiedTime=LastModifiedTime_0, status=Status_0], orderID=OrderId_0], Order [buyerUserID=BuyerUserId_1, checkoutStatus=CheckoutStatus [eBayPaymentStatus=EBayPaymentStatus_1, lastModifiedTime=LastModifiedTime_1, status=Status_1], orderID=OrderId_1], Order [buyerUserID=BuyerUserId_2, checkoutStatus=CheckoutStatus [eBayPaymentStatus=EBayPaymentStatus_2, lastModifiedTime=LastModifiedTime_2, status=Status_2], orderID=OrderId_2]], paginationResult=PaginationResult [totalNumberOfEntries=10, totalNumberOfPages=5], timestamp=2007-12-10T16:12:55.184Z, version=539]
需要注意的是,在反序列化时(Json字符串转Java对象),如果Json字符串有冗余(Json属性在Java对象中找不到对应的字段),则会抛出UnrecognizedPropertyException异常,此时可以设置以下属性:
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);







你可能感兴趣的:(JavaEE)