반응형
자바(JAVA) 실습 - json data 객체(Object)에 매핑(Mapping) (2) - json simple
환경 OpenJDK 1.8
1. json 파일 문자열(String)로 읽기
2. 문자열을 객체로 매핑
[ TestSimpleJson.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
package test.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import test.model.Product;
public class TestSimpleJson {
private static final String FILELOCATION = "test/init.json";
public static void main(String[] args) {
Long start = System.nanoTime();
String result = readJsonFile();
// System.out.println("result: " + result);
List<Product> productList = getProductList(result);
Long end = System.nanoTime();
Long elapsedTime = end - start;
System.out.println("productList: " + productList.toString());
System.out.println("Elapsed Time: " + elapsedTime + " nano sec.");
}
private static String readJsonFile() {
ClassLoader classLoader = TestSimpleJson.class.getClassLoader();
StringBuilder sb = new StringBuilder();
try (InputStream inputStream = classLoader.getResourceAsStream(FILELOCATION);
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException();
}
return sb.toString();
}
private static Map getMapFromString(String jsonString) {
JSONParser jsonParser = new JSONParser();
Map map = null;
try {
Object object = jsonParser.parse(jsonString);
map = (Map) object;
if (map.isEmpty()) {
throw new RuntimeException();
}
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException();
}
return map;
}
private static List<Product> getProductList(String jsonString) {
Map map = getMapFromString(jsonString);
JSONArray jsonArray = (JSONArray) map.get("product");
List<Product> productList = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject prodObject = (JSONObject) jsonArray.get(i);
Product product = new Product(prodObject.get("productName").toString(),
prodObject.get("productDescription").toString(),
new BigDecimal(prodObject.get("productPrice").toString()));
productList.add(product);
}
return productList;
}
}
|
반응형