Java
[Java] json 파일 읽기, 파싱 -Mac
brightGarden02
2022. 12. 13. 11:13
json을 읽기 위해서 build.gradle에 라이브러리를 추가한다.
// https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
파일경로 지정
Mac에는 C드라이브가 아닌 Macintosh HD가 있다.
json 파일을 읽을 때
아래와 같이 파일 경로를 지정할 수 있으나 에러가 난다.
Reader reader = new FileReader("/Macintosh HD/Users/won/Downloads/response.json");
따라서 경로에 Macintosh HD를 포함하지 않는다.
Reader reader = new FileReader("/Users/won/Downloads/response.json");
전체 코드
import coding.example.member.entity.Member;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import java.io.FileReader;
import java.io.Reader;
@SpringBootApplication
@OpenAPIDefinition(info = @Info(title = "APIs", version = "0.0.1", description = "APIs v0.0.1"))
public class ExampleApplication {
public static void main(String[] args) throws Exception {
JSONParser parser = new JSONParser();
// JSON 파일 읽기
Reader reader = new FileReader("/Users/won/Downloads/response.json");
JSONObject jsonObject = (JSONObject) parser.parse(reader);
String value = (String) jsonObject.get("Key값 입력");
System.out.println(value);
json은 key, value로 이루어져 있으므로
해당 key를 통해 value를 받아온다.