반응형
자바(JAVA) 실습 - json data 객체(Object)에 매핑(Mapping) (3) - Gson
환경 OpenJDK 1.8
1. json 파일 문자열(String)로 읽기
2. 문자열을 객체로 매핑
[ TestGson.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
|
package test.gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import test.model.Product;
public class TestGson {
private static final String FILELOCATION = "test/init.json";
public static void main(String[] args) {
Long start = System.nanoTime();
String result = readJsonFile(FILELOCATION);
// 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(String file) {
ClassLoader classLoader = TestGson.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();
}
return sb.toString();
}
private static List<Product> getProductList(String jsonString) {
JsonObject jsonObject = new Gson().fromJson(jsonString, JsonObject.class);
JsonElement productElement = jsonObject.get("product");
JsonArray prodElementAsJsonArray = productElement.getAsJsonArray();
List<Product> productList = new ArrayList<>();
for (JsonElement prodElement : prodElementAsJsonArray) {
JsonObject prodObject = prodElement.getAsJsonObject();
Product product = new Product();
product.setProductName(prodObject.get("productName").toString());
product.setProductDescription(prodObject.get("productDescription").toString());
product.setProductPrice(prodObject.get("productPrice").getAsBigDecimal());
productList.add(product);
}
return productList;
}
}
|
반응형
'JAVA 자바 > JAVA 실습' 카테고리의 다른 글
[JAVA 실습 #8] javap 정리 (0) | 2021.05.03 |
---|---|
[JAVA 실습 #7] json data 객체(Object)에 매핑(Mapping) (4) - Jackson (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 |
[JAVA 실습 #6] 핸드폰번호 마스킹 - StringBuilder, charArray 활용 (0) | 2021.03.22 |