jackson 변환 json

8920 단어 Jackson
잭슨은 자바 대상을 json 대상이나 json을 자바 대상으로 변환할 수 있으며 json을 정보의 매개체로 활용하여 서비스 측과 클라이언트가 서로 전달할 수 있다. 현재android/이동 개발에 필수적인 잭슨은 json이다.
테스트 클래스:

package com.demo.test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.demo.entity.Account;

public class JacksonTest {
	private JsonGenerator jsonGenerator = null;
	private ObjectMapper objectMapper = null;
	private Account bean = null;
	
	@Before
	public void init() {
		bean = new Account();
		bean.setAddress("CHINA-BJ");
		bean.setEmail("[email protected]");
		bean.setId(1);
		bean.setName("haha");
		
		objectMapper = new ObjectMapper();
		
		try {
			jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@After
	public void destory() {
		try {
			if (jsonGenerator != null) {
				jsonGenerator.flush();
			}
			if (!jsonGenerator.isClosed()) {
				jsonGenerator.close();
			}
			jsonGenerator = null;
			objectMapper = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void writeEntityJson() {
		try {
			System.out.println("jsonGenerator");
			//writeObject    java  ,eg:JavaBean/Map/List/Array
			jsonGenerator.writeObject(bean);
			System.out.println();
			System.out.println("objectMapper");
			//writeValue writeObject      
			objectMapper.writeValue(System.out, bean);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void writeMapJson() {
		try{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("name", bean.getName());
			map.put("account", bean);
			bean = new Account();
			bean.setAddress("CHINA-GZ");
			bean.setEmail("[email protected]");
			map.put("account2", bean);
			
			System.out.println("jsonGenerator");
			jsonGenerator.writeObject(map);
			System.out.println();
			System.out.println("objectMapper");
			objectMapper.writeValue(System.out, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void writeListJson() {
		try{
			List<Account> accounts = new ArrayList<Account>();
			accounts.add(bean);
			bean = new Account();
			bean.setId(2);
			bean.setName("lala");
			bean.setAddress("CHINA-GZ");
			bean.setEmail("[email protected]");
			accounts.add(bean);
			
			System.out.println("jsonGenerator");
			jsonGenerator.writeObject(accounts);
			System.out.println();
			System.out.println("objectMapper");
			
			System.out.println("1###" + objectMapper.writeValueAsString(accounts));
			System.out.println("2###");
			objectMapper.writeValue(System.out, accounts);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void writeOthersJson() {
		try{
			String[] arr = {"abc", "def", "jhi"};
			System.out.println("jsonGenerator");
			String str = "Hello Jackson!";
			//byte
			jsonGenerator.writeBinary(str.getBytes());
			//boolean
			jsonGenerator.writeBoolean(true);
			//null
			jsonGenerator.writeNull();
			//float
			jsonGenerator.writeNumber(2.5f);
			//char
			jsonGenerator.writeRaw("c");
			//String
			jsonGenerator.writeRaw(str, 1, 5);
			//String
			jsonGenerator.writeRawValue(str, 5, 5);
			//String
			jsonGenerator.writeString(str);
			
			jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str));
			
			System.out.println();
			//Objcet {"user":{"name":"lala","sex":true,"age":26},"infos":[22,"Hello Jackson"]}
			jsonGenerator.writeStartObject(); //{
			jsonGenerator.writeObjectFieldStart("user"); //user:{
			jsonGenerator.writeStringField("name", "lala"); //name:lala
			jsonGenerator.writeBooleanField("sex", true); // sex:true
			jsonGenerator.writeNumberField("age", 26); // age:26
			jsonGenerator.writeEndObject(); //}
			
			//Array
			jsonGenerator.writeArrayFieldStart("infos"); //infos:[
			jsonGenerator.writeNumber(22); //22
			jsonGenerator.writeString("Hello Jackson"); //Hello Jackson
			jsonGenerator.writeEndArray(); //]
			jsonGenerator.writeEndObject(); //}
			
			// complex object
			jsonGenerator.writeStartObject();
			jsonGenerator.writeObjectField("account", bean);
			jsonGenerator.writeObjectField("infos", arr);
			jsonGenerator.writeEndObject();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void readJson2Entity() {
		try{
		String json = "{\"address\":\"SH\",\"name\":\"lala\",\"id\":1,\"email\":\"[email protected]\"}";
		Account account = objectMapper.readValue(json, Account.class);
		System.out.println(account.getName());
		System.out.println(account);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void others() {
		String json = "";
		try {
			//readJson2List
			List<LinkedHashMap<String, Object>> list = objectMapper.readValue(json, List.class);
			//readJson2Array
			Account[] arr = objectMapper.readValue(json, Account[].class);
			//readJson2Map
			Map<String, Map<String, Object>> map = objectMapper.readValue(json, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
}


객체:

package com.demo.entity;

import java.io.Serializable;

public class Account implements Serializable{

	private static final long serialVersionUID = -5985853834387791596L;
	private int id;
	private String name;
	private String email;
	private String address;
	private Birthday birthday;
	
	public Account () {
		super();
	}
	
	public Account(int id, String name, String email, String address,
			Birthday birthday) {
		super();
		this.id = id;
		this.name = name;
		this.email = email;
		this.address = address;
		this.birthday = birthday;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Birthday getBirthday() {
		return birthday;
	}
	public void setBirthday(Birthday birthday) {
		this.birthday = birthday;
	}
	@Override
	public String toString() {
		return "Account [id=" + id + ", name=" + name + ", email=" + email
				+ ", address=" + address + ", birthday=" + birthday + "]";
	}
	
}


ps: 원래 인터넷에서 잭슨으로 xml을 쉽게 만들 수 있는 것을 보았는데 XmlMapper는 이미 잭슨-alljar 패키지에 존재하지 않아요. 네티즌들이 방법을 찾았어요. 그런데 저는 아직 시도하지 않아서 xml로 전환하는 테스트 방법이 없어요.
참조 자료:
http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html
http://wiki.fasterxml.com/JacksonInFiveMinutes
http://blog.sina.com.cn/s/blog_9d0ce63d01012vmd.html

좋은 웹페이지 즐겨찾기