๐ก ํ์ฑ(Parsing)์ด๋
์ปดํจํฐ ๊ณผํ์์ ์ ๋ ฅ๋ ๋ฐ์ดํฐ๋ฅผ ํด์ํ๊ณ ๊ตฌ์กฐํํ๋ ๊ณผ์ ์ ์๋ฏธํฉ๋๋ค. ์ผ๋ฐ์ ์ผ๋ก ํ์ฑ์ ํ ์คํธ ๋ฐ์ดํฐ๋ฅผ ํน์ ํ์์ผ๋ก ๋ณํํ๊ฑฐ๋, ํ ์คํธ ๋ฐ์ดํฐ์์ ์ ์ฉํ ์ ๋ณด๋ฅผ ์ถ์ถํ๋ ๋ฐ ์ฌ์ฉ๋ฉ๋๋ค. ํ์ฑ์ ํตํด ์์ ๋ฐ์ดํฐ๋ฅผ ์ปดํจํฐ๊ฐ ์ดํดํ๊ณ ์ฒ๋ฆฌํ ์ ์๋ ๊ตฌ์กฐ๋ก ๋ณํํ ์ ์์ต๋๋ค.
JSON(JavaScript Object Notation)์ ๊ฒฝ๋ ๋ฐ์ดํฐ ๊ตํ ํ์์ผ๋ก, ์๋ฐ์คํฌ๋ฆฝํธ ๊ฐ์ฒด ํ๊ธฐ๋ฒ์ ๊ธฐ๋ฐ์ผ๋ก ํ๋ค. JSON ํ์ฑ์ JSON ํ์์ ๋ฌธ์์ด์ ํ๋ก๊ทธ๋๋ฐ ์ธ์ด์์ ์ฌ์ฉํ ์ ์๋ ๊ฐ์ฒด๋ก ๋ณํํ๋ ๊ณผ์ ์ด๋ค.
{
"name": "John Doe",
"age": 30,
"email": "johndoe@example.com"
}
[
"apple",
"banana",
"cherry"
]
์ซ์(Number):
๋ถ๋ฆฌ์ธ(Boolean):
๋(Null):
[
{
"name": "John Doe",
"age": 30,
"isStudent": false
},
{
"name": "John Doe",
"age": 30,
"isStudent": false
}
]
{
"name": "John Doe",
"age": 30,
"isStudent": false,
"scores": [95, 87, 92],
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
},
"courses": [
{
"name": "Math",
"grade": "A"
},
{
"name": "English",
"grade": "B"
}
],
"graduationYear": null
}
JSON ํ์ฑ์ ์ํด GSON ๋ผ์ด๋ธ๋ฌ๋ฅผ ์ถ๊ฐ ํ๋ค.
(๋น๋ ๋๊ตฌ๋ฅผ ์ฌ์ฉํ์ง ์๋ ๊ฒฝ์ฐ, ์ง์ JAR ํ์ผ์ ๋ค์ด๋ก๋ํ๊ณ ํ๋ก์ ํธ์ ์ถ๊ฐํด์ผ ํ๋ค.)
import com.google.gson.Gson;
public class MainTest1 {
public static void main(String[] args) {
// Gson <-- ํ์ฌ ์ฌ์ฉ ๋ถ๊ฐ
// lib ํด๋์ Gson ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ถ๊ฐ
// ์ฐ๋ฆฌ ์์ค ์ฝ๋์์ ์ฌ์ฉํ๊ธฐ ์ํด ์ค์ ์ด ํ์ ํ๋ค.
// ํ๋ก์ ํธ ์์ฑ์์ ๋น๋ํจ์ค ๋ค์ด๊ฐ์ ํด๋์ค ํจ์ค์ add jars ๋ฑ๋ก
Gson gson = new Gson();
gson.fieldNamingStrategy();
} // end of main
} // end of class
{
"name": "ํ๊ธธ๋",
"age": 21,
"subjects": ["์ํ", "๋ฌผ๋ฆฌ", "์ปดํจํฐ ๊ณผํ"]
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonExample {
public static void main(String[] args) {
//
Student student1 = new Student("๊ณ ๊ธธ๋", 40, "์ ์ํ๊ณผ");
Student student2 = new Student("๋๋ฆฌ", 5, "๋ฌธ์ ํ๊ณผ");
//
Student[] studentArr = {student1, student2};
// --> ํน์ ํ์(๊ตฌ์กฐํ) ์๋ ๋ฌธ์์ด๋ก ๋ณํ ํ๊ณ ์ถ๋ค.. --> JSON ํํ
Gson gson = new GsonBuilder().setPrettyPrinting().create();
// ๊ฐ์ฒด๋ฅผ --> json ํ์์ ๋ฌธ์์ด๋ก ๋ณํ ์์ผ! --> ๋ฉ์๋ toJson()
String student1Str = gson.toJson(student1);
System.out.println(student1Str);
// setPrettyPrinting -> ์ด์๊ฒ ์ถ๋ ฅํ๋ผ ์ต์
..
Gson gson2 = new Gson();
String studednt2Str = gson2.toJson(student2);
System.out.println(studednt2Str);
// ๊ฐ์ฒด์์ ---> ๋ฌธ์์ด ํํ๋ก ๊ฐ๋ฅ ๊ทธ๋ผ ๋ฐ๋๋ก๋ ์ด๋ป๊ฒ ํ์ง??
// ๋ฌธ์์ด์์ ---> ํด๋์ค ํํ๋ก ์ด๋ป๊ฒ ๋ณ๊ฒฝํ ๊น?
// Object ํํ๋ก ๋ณํ
Student studentObject = gson.fromJson(student1Str, Student.class);
System.err.println(studentObject.getName());
// ๋ฐฐ์ด ํํ๋ก ๋ณํ
Student[] StringArr = gson.fromJson(gson.toJson(studentArr), Student[].class);
System.err.println(StringArr);
for (Student student : StringArr) {
System.err.println(student.toString());
}
System.out.println("-----------------------------");
System.out.println(gson.toJson(StringArr));
}
}
JSON ํ์ฑ ์ฐ์ต (0) | 2024.06.07 |
---|---|
(๊ณต๋ถ) ์ฐ๊ฒฐ (0) | 2024.06.05 |
[JAVA] ๋คํธ์ํฌ ํ๋กํ ์ฝ (0) | 2024.05.24 |
[JAVA] 1: N ์์ผ ์๋ฐฉํฅ ํต์ (1) | 2024.05.24 |
[JAVA] 1:1 ์๋ฐฉํฅ ํต์ (์ฑํ ๊ธฐ๋ณธ ๊ธฐ๋ฅ ๊ตฌํ) (0) | 2024.05.24 |