자바

[Java] JSON 변환하기 : json-simple

MY_STUDY 2024. 12. 3. 14:49

문자열을 JSON으로 변환

1. 라이브러리 추가하기

<dependency>      
	<groupId>com.googlecode.json-simple</groupId>      
	<artifactId>json-simple</artifactId>      
	<version>1.1.1</version>     
</dependency>

 

JSON 변환을 위한 라이브러리를 pom.xml 파일에 추가한다.

 

 

2. 문자열을 JSON으로 변환하기

public class StringToJson {    
	public static void main(String[] args) throws ParseException {   
      
		// JSON 으로 파싱할 문자열        
		String str = "{\"name\" : \"book\", \"id\" : 3, \"price\" : 2000}";
         
		// JSONParser로 JSONObject로 변환        
		JSONParser parser = new JSONParser();        
		JSONObject jsonObject = (JSONObject) parser.parse(str);         

		// JSON 객체의 값 읽어서 출력하기        
		System.out.println(jsonObject.get("name")); // book        
		System.out.println(jsonObject.get("id")); // 3        
		System.out.println(jsonObject.get("price")); // 2000     
	}
}

 

 

 

 

 

JSON을 문자열로 반환

JSONObject jo1 = new JSONObject();
jo1.put("title", "제목1");
jo1.put("content", "내용1");

JSONObject jo2 = new JSONObject();
jo2.put("title", "제목2");
jo2.put("content", "내용2");

JSONArray ja = new JSONArray();
ja.add(jo1);
ja.add(jo2);

System.out.println(ja.toJSONString());
실행 결과 : [{"title":"제목1","content":"내용a1"},{"title":"제목2","content":"내용2"}]