使用Jackson时 JSON字段与java对象字段映射

使用Jackson时 JSON字段与java对象字段映射

package com.zto.demo;

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

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.CollectionType;


public class JacksonTest {

	public static void main(String[] args) throws JsonParseException,
			JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();

		//将JSON转List集合
		String expected = "[{\"PROBLEM_NAME\":\"催查件\"},{\"PROBLEM_NAME\":\"客户拒收\"}]";
		CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, ProblemPiece.class);
		List<ProblemPiece> problemPieceList = mapper.readValue(expected,listType);
		for (ProblemPiece p : problemPieceList) {
			System.out.println(p.getProblemName());
		}
		//将对象装JSON
		ProblemPiece problemPiece = new ProblemPiece();
		problemPiece.setProblemName("高伟刚");
		String problemPieceJson = mapper.writeValueAsString(problemPiece); 
		System.out.println(problemPieceJson);

	}

	public static class ProblemPiece {

		@JsonProperty("PROBLEM_NAME")
		private String problemName;

		public String getProblemName() {
			return problemName;
		}

		public void setProblemName(String problemName) {
			this.problemName = problemName;
		}

	}

}

猜你喜欢

转载自weigang-gao.iteye.com/blog/2377861