반응형
1. Gson jar 파일 lib 추가
- gson-2.3.1.jar
2. Object객체를 생성
- JsonObject jsonobject = new JsonObject();
3. gson 객체 만들기
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
* Gson gson = new Gson(); : 일자로 나옴
* Gson gson = new GsonBuilder().setPrettyPrinting().create(); : 자동 개행 및 줄 바꿈
4. json 형태로 만들기
- String json = gson.toJson(jsonobject);
5. 파일에 쓰기
- JsonElement element = jsonParser.parse(new FileReader("C:\\Users\\USER\\Desktop\\java-workspaces\\JsonTest\\jsontestfile\\json.txt"));
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
|
package json;
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class JsonTest {
public static void main(String[] args) {
FileWriter writer=null;
JsonObject jsonobject = new JsonObject();
jsonobject.addProperty("company", "tistory");
jsonobject.addProperty("address", "seoul");
jsonobject.addProperty("number", "0212345678");
JsonObject name1Info = new JsonObject();
name1Info.addProperty("name", "kim");
name1Info.addProperty("age", "29");
name1Info.addProperty("isNew", true);
JsonObject name2Info = new JsonObject();
name2Info.addProperty("name", "park");
name2Info.addProperty("age", "27");
name2Info.addProperty("isNew", true);
JsonObject name3Info = new JsonObject();
name3Info.addProperty("name", "lee");
name3Info.addProperty("age", "26");
name3Info.addProperty("isNew", true);
JsonArray infoArray = new JsonArray();
infoArray.add(name1Info);
infoArray.add(name2Info);
infoArray.add(name3Info);
jsonobject.add("newEmployees", infoArray);
System.out.println(jsonobject);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(jsonobject);
try {
writer = new FileWriter("C:\\Users\\USER\\Desktop\\java-workspaces\\JSonTest\\jsontestfile\\gson.json");
writer.write(json);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
cs |
json 파일 결과
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
{
"company": "tistory",
"address": "seoul",
"number": "0212345678",
"newEmployees": [
{
"name": "kim",
"age": "29",
"isNew": true
},
{
"name": "park",
"age": "27",
"isNew": true
},
{
"name": "lee",
"age": "26",
"isNew": true
}
]
}
|
cs |
반응형