브라우저에서 위 URL 로 접속해 보면 JSON 문자열을 다음과 같다.
1 2 3 4 5 6 7 | { type: "success", value: { id: 10, quote: "Really loving Spring Boot, makes stand alone Spring apps easy." } } |
요것을 처리하는 예제 코드
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 | import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonTest { public static void main(String[] args) throws JsonParseException, JsonMappingException, MalformedURLException, IOException { ObjectMapper mapper = new ObjectMapper(); // URL 에 있는 JSON String 을 Map으로 변환하기 Map<String, Object> data = mapper.readValue( new TypeReference<Map<String,Object>>(){}); // {type=success, value={id=9, quote=So easy it is to switch container in #springboot.}} System.out.println(data); // {id=9, quote=So easy it is to switch container in #springboot.} System.out.println(data.get( "value" )); // Map을 JSON String 으로 변환 // {"type":"success","value":{"id":9,"quote":"So easy it is to switch container in #springboot."}} System.out.println(mapper.writeValueAsString(data)); // Map을 보기쉬운 JSON String 으로 변환 /* { "type" : "success", "value" : { "id" : 9, "quote" : "So easy it is to switch container in #springboot." } } */ System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(data)); } } |