본문 바로가기
Language/Java

[JAVA] Jackson을 활용한 JSON 변환 예제 / JsonUtils

by 나비와꽃기린 2016. 11. 4.
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.



Jackson lib를 활용해서 JSON 객체를 파싱 및 변환하는 예제를 다루려고 한다.

pom.xml에 jackson 관련 디펜던시를 추가하거나 jackson lib를 다운받아 lib 폴더에 추가해주자.

<dependency>
	<groupId>org.codehaus.jackson</groupId>
	<artifactId>jackson-mapper-asl</artifactId>
	<version>1.9.13</version>
</dependency>

jackson download 경로 :: http://www.java2s.com/Code/Jar/j/Downloadjacksonall190jar.htm



(1) json string -> map 으로 변환

public static void main(String[] args) {
	 
	try {
		
		System.out.println("-------------------JSON String 을 MAP 으로 변환-----------------------");
		ObjectMapper mapper = new ObjectMapper();
		String json = "{ \"name\" : \"mkgil\" , \"age\" : 25  }";

		Map<String, Object> map = new HashMap<String, Object>();
		map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});

		System.out.println(map);
		System.out.println(map.get("name"));
		
	} catch (JsonGenerationException e) {
		e.printStackTrace();
	} catch (JsonMappingException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}

}

<<output>>

{name=mkgil, age=25}

mkgil



public static void main(String[] args) {
 
	try {
		ObjectMapper mapper = new ObjectMapper();
		String json = "{\"name\":\"mkyong\", \"age\":29, \"messages\" : [\"msg 1\",\"msg 2\",\"msg 3\"]  }";

		Map<Object, Object> map = new HashMap<Object, Object>();

		// convert JSON string to Map
		map = mapper.readValue(json, new TypeReference<Map<Object, Object>>(){});

		System.out.println(map);
		ArrayList aL = (ArrayList) map.get("messages");
		System.out.println( aL.get(2) );
		
		
	} catch (JsonGenerationException e) {
		e.printStackTrace();
	} catch (JsonMappingException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}


}

<<output>>

{name=mkyong, age=29, messages=[msg 1, msg 2, msg 3]}

msg 3



(2) map -> json string 으로 변환

public static void main(String[] args) {
	 
	try {
		
		System.out.println("-------------------MAP을 JSON String으로 변환-----------------------");
		ObjectMapper mapper = new ObjectMapper();
		String json2 = "";

		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("name", "mkgil");
		map2.put("age", 25);

		//json2 = mapper.writeValueAsString(map2);
		json2 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map2);
		System.out.println(json2);
		
	} catch (JsonGenerationException e) {
		e.printStackTrace();
	} catch (JsonMappingException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}

}

<<output>>

{

  "name" : "mkgil",

  "age" : 25

}


(3) map을 json file로 쓰기

public static void main(String[] args) {
 
try {
	
	ObjectMapper mapper = new ObjectMapper();

	Map<String, Object> map = new HashMap<String, Object>();
	map.put("name", "mkgil");
	map.put("age", 25);

	List<Object> list = new ArrayList<Object>();
	list.add("msg 1");
	list.add("msg 2");
	list.add("msg 3");

	map.put("messages", list);

	mapper.writeValue(new File("c:\\aaa\\user.json"), map);
	
} catch (JsonGenerationException e) {
	e.printStackTrace();
} catch (JsonMappingException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
}

}

<<output>>




(4) json file을 읽어 map으로

public static void main(String[] args) {
 
	try {

		ObjectMapper mapper = new ObjectMapper();

		Map<String, Object> map = mapper.readValue(new File("c:\\aaa\\user.json"), new TypeReference<Map<String, Object>>() {});

		System.out.println(map.get("name"));
		System.out.println(map.get("age"));
		System.out.println(map.get("messages"));
		
		ArrayList<String> list = (ArrayList<String>) map.get("messages");

		for (String msg : list) {
			System.out.println(msg);
		}


	} catch (JsonGenerationException e) {
		e.printStackTrace();
	} catch (JsonMappingException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}


}

<<output>>

mkgil

25

[msg 1, msg 2, msg 3]

msg 1

msg 2

msg 3



(4) JsonUtils CLASS



import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonUtils {
	
	private JsonUtils(){}
	
	public static Map stringToJsonMap(String json){
		return stringToObject(json, HashMap.class);
	}
	
	public static Object stringToJsonClass(String json, Class clazz){
		return stringToObject(json, clazz);
	}
	
	public static <T> T stringToObject(String jsonString, Class<T> valueType){
		try {
			return new ObjectMapper().readValue(jsonString, valueType);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String jsonToString(Object jsonObject){
		return objectToString(jsonObject);
	}
	
	public static String gainJsonToString(Object jsonObject){
		return gainJsonToString(jsonObject, true);
	}
	
	public static String gainJsonToString(Object jsonObject, boolean resultAddFlag){
		if(resultAddFlag){
			Map m = new HashMap();
			m.put("result", jsonObject);
			return objectToString(m);
		}else{
			return objectToString(jsonObject);
		}
	}
	
	public static String objectToString(Object json) {
		ObjectMapper om = new ObjectMapper();
		try {
			return om.writeValueAsString(json);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	

	
	public static String callbackObjectToString(String callback , Object json){
		String reval = objectToString(json);
		if(!"".equals(callback)){
			reval = callback+"("+reval+")";
		}
		
		return reval; 
	}
}




// ps 

GSON과 Jackson을 비교설명이 잘 된 사이트가 있네요

:: http://tomining.tistory.com/27