Object Mapper 라이브러리 사용관련 자료 조사
며칠전 아는형님의 소개로 Object Mapper에 대해 알게 되었다.
1. 사용방법에 대해 잘 나와있다.
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
---------------------------------------------------------------------------------------------------------------------------------------
In this tutorial, we show you how to use Jackson 1.x data binding to convert Java object to / from JSON.
Jackson 1.x is a maintenance project, please use Jackson 2.x instead.
This tutorial is obsolete, no more update, please refer to the latest Jackson 2 tutorial – Object to / from JSON.
1. Quick Reference
1.1 Convert Java object to JSON, writeValue(...)
ObjectMapper mapper = new ObjectMapper();
User user = new User();
//Object to JSON in file
mapper.writeValue(new File("c:\\user.json"), user);
//Object to JSON in String
String jsonInString = mapper.writeValueAsString(user);
1.2 Convert JSON to Java object, readValue(...)
ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'mkyong'}";
//JSON from file to Object
User user = mapper.readValue(new File("c:\\user.json"), User.class);
//JSON from String to Object
User user = mapper.readValue(jsonInString, User.class);
P.S All examples are tested with Jackson 1.9.13
2. Jackson Dependency
For Jackson 1.x, it contains 6 separate jars for different purpose, in most cases, you just need jackson-mapper-asl
.
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
3. POJO (Plain Old Java Object)
An User object for testing.
package com.mkyong.json;
import java.util.List;
public class User {
private String name;
private int age;
private List<String> messages;
//getters and setters
}
4. Java Object to JSON
Convert an user
object into a JSON formatted string.
package com.mkyong.json;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
//For testing
User user = createDummyUser();
try {
//Convert object to JSON string and save into file directly
mapper.writeValue(new File("D:\\user.json"), user);
//Convert object to JSON string
String jsonInString = mapper.writeValueAsString(user);
System.out.println(jsonInString);
//Convert object to JSON string and pretty print
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
System.out.println(jsonInString);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static User createDummyUser(){
User user = new User();
user.setName("mkyong");
user.setAge(33);
List<String> msg = new ArrayList<>();
msg.add("hello jackson 1");
msg.add("hello jackson 2");
msg.add("hello jackson 3");
user.setMessages(msg);
return user;
}
}
Output
//new json file is created in D:\\user.json"
{"name":"mkyong","age":33,"messages":["hello jackson 1","hello jackson 2","hello jackson 3"]}
{
"name" : "mkyong",
"age" : 33,
"messages" : [ "hello jackson 1", "hello jackson 2", "hello jackson 3" ]
}
5. JSON to Java Object
Read JSON string and convert it back to a Java object.
package com.mkyong.json;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
// Convert JSON string from file to Object
User user = mapper.readValue(new File("G:\\user.json"), User.class);
System.out.println(user);
// Convert JSON string to Object
String jsonInString = "{\"age\":33,\"messages\":[\"msg 1\",\"msg 2\"],\"name\":\"mkyong\"}";
User user1 = mapper.readValue(jsonInString, User.class);
System.out.println(user1);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
User [name=mkyong, age=33, messages=[hello jackson 1, hello jackson 2, hello jackson 3]]
User [name=mkyong, age=33, messages=[msg 1, msg 2]]
6. @JsonView
@JsonView
has been supported in Jackson since version 1.4, it lets you control what fields to display.
6.1 A simple class.
package com.mkyong.json;
public class Views {
public static class NameOnly{};
public static class AgeAndName extends NameOnly{};
}
6.2 Annotate on the fields you want to display.
package com.mkyong.json;
import java.util.List;
import org.codehaus.jackson.map.annotate.JsonView;
public class User {
@JsonView(Views.NameOnly.class)
private String name;
@JsonView(Views.AgeAndName.class)
private int age;
private List<String> messages;
//getter and setters
}
6.3 Enable the @JsonView
via writerWithView()
.
package com.mkyong.json;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
public class JacksonExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
//By default all fields without explicit view definition are included, disable this
mapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
//For testing
User user = createDummyUser();
try {
//display name only
String jsonInString = mapper.writerWithView(Views.NameOnly.class).writeValueAsString(user);
System.out.println(jsonInString);
//display namd ana age
jsonInString = mapper.writerWithView(Views.AgeAndName.class).writeValueAsString(user);
System.out.println(jsonInString);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static User createDummyUser(){
User user = new User();
user.setName("mkyong");
user.setAge(33);
List<String> msg = new ArrayList<>();
msg.add("hello jackson 1");
msg.add("hello jackson 2");
msg.add("hello jackson 3");
user.setMessages(msg);
return user;
}
}
Output
{"name":"mkyong"}
{"name":"mkyong","age":33}
2. 한글이라서 좋고 깔끔하게 설명을 잘 해놓으셨다.
http://noritersand.tistory.com/240
----------------------------------------------------------------------------------------------------------------------------------------
관련 문서
- http://wiki.fasterxml.com/JacksonDownload
- jackson-annotations-2.2.3.jar
- jackson-core-2.2.3.jar
- jackson-databind-2.2.3.jar
Map - JSON간 변환
writeValueAsString()
writeValueAsString( value )
- value: String 타입으로 변환할 대상
readValue()
readValue( arg, type )
- arg: 지정된 타입으로 변환할 대상
- type: 대상을 어떤 타입으로 변환할것인지 클래스를 명시한다. Class객체, TypeReference객체가 올 수 있다.
ex)
mapper.readValue(arg, ArrayList.class); mapper.readValue(arg, new ArrayList<HashMap<String, String>>().getClass()); mapper.readValue(arg, new TypeReference<ArrayList<HashMap<String, String>>>(){}); | cs |
map
맵 타입이 JSON 형식의 String 타입으로 변환된다. 자바스크립트에 JSON을 넘겨줄 때 유용하다.
import com.fasterxml.jackson.databind.ObjectMapper; public class Test2 { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); HashMap<String, String> map = new HashMap<String, String>(); map.put("name", "steave"); map.put("age", "32"); map.put("job", "baker"); System.out.println(map); System.out.println(mapper.writeValueAsString(map)); } } // {age=32, name=steave, job=baker} // {"age":"32","name":"steave","job":"baker"} | cs |
위와 반대로 JSON을 맵 타입으로 변환하려면 다음처럼 작성한다:
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; public class Test2 { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); HashMap<String, String> map = new HashMap<String, String>(); String jsn = "{\"age\":\"32\",\"name\":\"steave\",\"job\":\"baker\"}"; map = mapper.readValue(jsn, new TypeReference<HashMap<String, String>>() {}); System.out.println(map); } } // {name=steave, age=32, job=baker} | cs |
List<Map>
다음은 view에 전달할 model이 List<map<?, ?>> 타입일 때 이를 JSON으로 변환하는 방법이다. 사용방법은 크게 다르지 않고 writeValueAsString, readValue 메서드를 사용하되 타입 명시만 달리한다.
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; public class Test2 { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); // map -> json ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>(); HashMap<String, String> map = new HashMap<String, String>(); map.put("name", "steave"); map.put("age", "32"); map.put("job", "baker"); list.add(map); map = new HashMap<String, String>(); map.put("name", "matt"); map.put("age", "25"); map.put("job", "soldier"); list.add(map); System.out.println(mapper.writeValueAsString(list)); // json -> map String jsn = "[{\"age\":\"32\",\"name\":\"steave\",\"job\":\"baker\"}," + "{\"age\":\"25\",\"name\":\"matt\",\"job\":\"soldier\"}]"; list = mapper.readValue(jsn, new TypeReference<ArrayList<HashMap<String, String>>>() {}); System.out.println(list); } } // [{"age":"32","name":"steave","job":"baker"},{"age":"25","name":"matt","job":"soldier"}] // [{name=steave, age=32, job=baker}, {name=matt, age=25, job=soldier}] | cs |
3. 설명이 디테일하여 참고하기 좋았다.
http://noritersand.tistory.com/240
----------------------------------------------------------------------------------------------------------------------------------------
This page will describe how to read JSON into Java object and write java object into JSON output using Jackson API. Jackson has different API like ObjectMapper, JsonParser and JsonGenerator etc. We can read JSON from different resources like String variable, file or any network. ObjectMapper is most important class which acts as codec or data binder. ObjectMapper can write java object into JSON file and read JSON file into java Object. Jackson provides faster Streaming API i.e JsonParser and JsonGenerator. JsonParser reads JSON file and JsonGenerator writes java object or map into JSON file using coded object. While creating java class to map to and from JSON we must keep a default constructor because Jackson API creates java class instance using default constructor.
Here we will cover below points.
Contents
- Gradle file to Resolve Jackson JAR Dependency
- Create JSON as String by Object using ObjectMapper.writeValueAsString()
- Write Object into JSON file using ObjectMapper.writeValue()
- Pretty Print JSON using ObjectWriter with DefaultPrettyPrinter
- Write java Map into JSON file using Jackson ObjectMapper
- Read JSON file into Object using ObjectMapper.readValue()
- Write Object into JSON file using JsonGenerator
- Pretty Print using JsonGenerator
- Write java map into JSON file using JsonGenerator
- Read JSON file using JsonParser and JsonNode
- Download Complete Source Code
Gradle file to Resolve Jackson JAR Dependency
Find the Gradle file to resolve Jackson JAR dependency in our project.
build.gradle
Create JSON as String by Object using ObjectMapper.writeValueAsString()
In Jackson JSON API org.codehaus.jackson.map.ObjectMapper is an important class. ObjectMapper is a codec or data binder that maps java object and JSON into each other. Here in this example we will convert java object into JSON string using writeValueAsString() method of ObjectMapper.
CreateJSONWithObjectMapper.java
Find the output.
Find the class that will be used to convert into JSON and read JSON into Java object. Find the Address class.
Address.java
Find the person class.
Person.java
Write Object into JSON file using ObjectMapper.writeValue()
In this example, we will create a java object and using ObjectMapper.writeValue() method, we will convert that java object into JSON file. writeValue() serializes java object to JSON.
WriteJSONWithObjectMapperOne.java
Find the output.
dataOne.json
Pretty Print JSON using ObjectWriter with DefaultPrettyPrinter
Jackson API can write pretty print JSON . For that we can use DefaultPrettyPrinter instance.
WriteJSONWithObjectMapperTwo.java
Find the output.
dataTwo.json
Write java Map into JSON file using Jackson ObjectMapper
If we have data into map, that can also be converted into JSON using ObjectMapper.
WriteJSONWithObjectMapperThree.java
Find the output.
dataThree.json
Read JSON file into Object using ObjectMapper.readValue()
To read JSON file into java object, Jackson provides ObjectMapper.readValue(). Find the input JSON file.
dataOne.json
Now find the java class to read the JSON.
ReadJSONWithObjectMapper.java
Find the output.
Write Object into JSON file using JsonGenerator
org.codehaus.jackson.JsonGenerator writes JSON using codec. To use JsonGenerator we can set codec as ObjectMapper() instance. In this example we will convert java object into JSON file.
WriteJSONWithJsonGeneratorOne.java
Find the output.
infoOne.json
Pretty Print using JsonGenerator
For pretty printing, Jackson provides DefaultPrettyPrinter that can be set to JsonGenerator instance.
WriteJSONWithJsonGeneratorTwo.java
Find the output.
infoTwo.json
Write java map into JSON file using JsonGenerator
Java map can be converted into JSON file using JsonGenerator.
WriteJSONWithJsonGeneratorThree.java
Find the output.
infoThree.json
Read JSON file using JsonParser and JsonNode
org.codehaus.jackson.JsonParser reads JSON file. JsonParser can read JSON as tree returning JsonNode. Find the input JSON file.
infoTwo.json
Now find the java class to read the JSON.
ReadJSONWithJsonParser.java
Find the output.
3. 필요한 부분만 잘설명 되어있다
http://noritersand.tistory.com/240
----------------------------------------------------------------------------------------------------------------------------------------
SON 문자열을 Map 이나 List Object 로 변환하는 것이랑
JSON 문자열을 xml 다루듯이 트래버싱 하는것,
Map 이나 List Object 를 JSON 문자열로 변환하는것 요래 정리를 해 보았다.
뭐 요정도만 알면 대충 할 수 있는건 다 할 수 있을듯하다. 뭐 필요하면 더 그때가서 더 찾아보면 되긋지~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | package test; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; public class Test { /** * @param args */ public static void main(String[] args) throws Exception{ // 테스트 데이터 : 맵에 string 2개랑 list 하나가 들어가 있는 형태 List<String> list = new ArrayList<String>(); list.add( "list1" ); list.add( "list2" ); list.add( "list3" ); Map<String, Object> d = new HashMap<String, Object>(); d.put( "list" , list); d.put( "a" , "va" ); d.put( "b" , "vb" ); //////////////////////////////////////////////// ObjectMapper om = new ObjectMapper(); // Map or List Object 를 JSON 문자열로 변환 String jsonStr = om.writeValueAsString(d); System.out.println( "object to json : " + jsonStr); // JSON 문자열을 Map or List Object 로 변환 Map<String, Object> m = om.readValue(jsonStr, new TypeReference<Map<String, Object>>(){}); System.out.println( "json to object : " + m); // JSON 문자열을 xml 다루는것과 비슷하게 트리로 맨들어서 트래버싱하기(Tree Model) JsonNode root = om.readTree(jsonStr); // 단일값 가져오기 System.out.println( "b의 값 : " + root.path( "b" ).getValueAsText()); // 배열에 있는 값들 가져오기 if ( root.path( "list" ).isArray() ){ Iterator<jsonnode> it = root.path( "list" ).iterator(); // 요래 해도 됨 // Iterator<jsonnode> it = root.path("list").getElements() while (it.hasNext()){ System.out.println(it.next().getTextValue()); } } // 이외 getXXXValue() 시리즈, findParent(), findValue() 등등 유용한 함수 많음~ } } |
'개발 공부 기록하기 > - Kotlin & Java' 카테고리의 다른 글
[Java] 문자열 나누기 특수문자에 대해 (0) | 2016.05.10 |
---|---|
[Java] 날짜 비교하기 & 요일의 날짜 얻기 (1) | 2016.04.06 |
Callable과 Thread (0) | 2016.02.04 |
Thread.sleep throw InterruptedException? (0) | 2016.01.07 |
[Java] 디렉토리내 일정기간 지난 파일 삭제 (0) | 2016.01.05 |