반응형
JSON: 개념과 활용, 그리고 자바와 자바스크립트에서의 사용법
JSON(JavaScript Object Notation)은 가볍고, 인간과 기계가 모두 읽기 쉬운 데이터 교환 형식입니다. 데이터를 키-값 쌍으로 표현하며, 주로 서버와 클라이언트 간 데이터 교환에 사용됩니다. 이번 글에서는 JSON의 개념, 구조, 자바스크립트와 자바에서 JSON을 다루는 방법을 살펴보겠습니다.
JSON이란 무엇인가?
JSON의 주요 특징:
- 간결성: 데이터를 표현하는 간단한 형식.
- 가독성: 사람과 기계가 쉽게 읽을 수 있음.
- 언어 독립적: 모든 프로그래밍 언어에서 사용 가능.
JSON 예제:
{
"name": "John Doe",
"age": 30,
"isMarried": false,
"children": ["Anna", "Billy"],
"address": {
"street": "123 Main St",
"city": "New York"
}
}
자바스크립트에서 JSON 다루기
1. JSON 문자열 생성
const jsonData = {
name: "John Doe",
age: 30,
isMarried: false,
children: ["Anna", "Billy"],
address: {
street: "123 Main St",
city: "New York"
}
};
// 객체를 JSON 문자열로 변환
const jsonString = JSON.stringify(jsonData);
console.log(jsonString);
2. JSON 문자열을 객체로 변환
const jsonString = '{"name":"John Doe","age":30}';
// JSON 문자열을 객체로 변환
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name); // "John Doe"
3. JSON 데이터 보내고 받기 (AJAX 사용)
// 데이터 전송
fetch("https://example.com/api", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: "John Doe", age: 30 })
})
.then(response => response.json())
.then(data => console.log(data));
자바에서 JSON 다루기
자바에서는 Jackson Databind 라이브러리를 주로 사용하여 JSON 데이터를 처리합니다.
1. 의존성 추가 (Maven):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.14.0</version>
</dependency>
2. JSON을 자바 객체로 변환
JSON 문자열:
{
"name": "John Doe",
"age": 30,
"isMarried": false
}
자바 클래스:
public class Person {
private String name;
private int age;
private boolean isMarried;
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isMarried() {
return isMarried;
}
public void setMarried(boolean married) {
isMarried = married;
}
}
JSON을 객체로 변환:
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonToObjectExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John Doe\",\"age\":30,\"isMarried\":false}";
ObjectMapper objectMapper = new ObjectMapper();
try {
Person person = objectMapper.readValue(jsonString, Person.class);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("Is Married: " + person.isMarried());
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. 자바 객체를 JSON으로 변환
import com.fasterxml.jackson.databind.ObjectMapper;
public class ObjectToJsonExample {
public static void main(String[] args) {
Person person = new Person();
person.setName("John Doe");
person.setAge(30);
person.setMarried(false);
ObjectMapper objectMapper = new ObjectMapper();
try {
String jsonString = objectMapper.writeValueAsString(person);
System.out.println("JSON String: " + jsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
JSON 데이터와 자바 클래스 매핑
복잡한 JSON 구조 예:
{
"name": "John Doe",
"age": 30,
"children": ["Anna", "Billy"],
"address": {
"street": "123 Main St",
"city": "New York"
}
}
자바 클래스:
import java.util.List;
public class Person {
private String name;
private int age;
private List<String> children;
private Address address;
// Getters and Setters
// ...
}
class Address {
private String street;
private String city;
// Getters and Setters
// ...
}
결론
JSON은 간결하고 효율적인 데이터 교환 형식으로, 자바스크립트와 자바에서 쉽게 사용할 수 있습니다. Jackson 라이브러리를 활용하면 JSON 데이터를 객체로 변환하거나 객체를 JSON으로 변환하는 작업을 간단히 처리할 수 있습니다. 이를 통해 서버-클라이언트 간 데이터 교환을 더욱 효율적으로 관리해 보세요!
반응형
'개발 부트캠프 > 백엔드' 카테고리의 다른 글
[Java] DBCP (0) | 2025.01.16 |
---|---|
[Java] Servlet Filter (0) | 2025.01.16 |
[Java] HTTP 요청 처리하기 (0) | 2025.01.16 |
[Java] SQL Injection (1) | 2025.01.10 |
[Java] 서블릿(Servlet) (0) | 2025.01.08 |