반응형
자바(JAVA) 실습 - json data 객체(Object)에 매핑(Mapping) (4) - Jackson
환경 OpenJDK 1.8
1. json 파일 스트림(stream)으로 읽기
2. JsonNode로 매핑
3. 객체(Object)로 매핑
[ TestJackson.java ]
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
65
66
67
68
69
|
package test.fasterxml;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import test.model.Product;
public class TestJackson {
private static final String FILELOCATION = "test/init.json";
public static void main(String[] args) {
Long start = System.nanoTime();
InputStream is = getStreamFromFile();
JsonNode productNode = getProductNode(is);
List<Product> productList = getProductFromNode(productNode);
Long end = System.nanoTime();
Long elapsedTime = end - start;
System.out.println("productList: " + productList.toString());
System.out.println("Elapsed Time: " + elapsedTime + " nano sec.");
}
private static InputStream getStreamFromFile() {
ClassLoader classLoader = TestJackson.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream(FILELOCATION);
if (is == null) {
throw new RuntimeException();
}
return is;
}
private static JsonNode getProductNode(InputStream is) {
if (is == null) {
throw new RuntimeException();
}
DataInputStream dis = new DataInputStream(is);
ObjectMapper objectMapper = new ObjectMapper();
try {
JsonNode productNode = objectMapper.readTree(dis).findPath("product");
return productNode;
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
private static List<Product> getProductFromNode(JsonNode productNode) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
List<Product> productList = new ArrayList<>();
productList = objectMapper.convertValue(productNode, new TypeReference<List<Product>>() {
});
return productList;
}
}
|
반응형
'JAVA 자바 > JAVA 실습' 카테고리의 다른 글
[JAVA 실습 #9] maven에서 이클립스 자바 컴파일러 활용 - plexus-compiler-eclipse (0) | 2021.05.28 |
---|---|
[JAVA 실습 #8] javap 정리 (0) | 2021.05.03 |
[JAVA 실습 #7] json data 객체(Object)에 매핑(Mapping) (3) - Gson (0) | 2021.03.27 |
[JAVA 실습 #7] json data 객체(Object)에 매핑(Mapping) (2) - json simple (0) | 2021.03.27 |
[JAVA 실습 #7] json data 객체(Object)에 매핑(Mapping) (1) - json 파일, 모델 객체(Object) (0) | 2021.03.27 |