val document = Jsoup.connect(url).ignoreContentType(true).execute().body();
ignoreContentType(true)을 이용하여 HTML뿐만 아니라 JSON 형식도 읽을 수 있도록 허용한다.
{
"data": {
"category": "신간",
"books": [
{
"no": "1",
"name": "ex1",
"description": "des1",
"author" : "auth1"
},
{
"no": "2",
"name": "ex2",
"description": "des2",
"author" : "auth2"
}
]
}
}
그럼 document안에 위와 같은 JSON 데이터가 들어간다.
@Entity
data class Books(
@JsonProperty("no")
val no: Int? = null,
@JsonProperty("name")
val name: String? = null,
@JsonProperty("description")
val description: String? = null
) : Serializable{
}
JSON 정보를 담을 객체를 생성한다.
val mapper = ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
객체에 존재하지 않는 필드인 author
를 무시하기 위해 DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
를 이용한다.
val books = mapper.readTree(document).get("data").get("books")
JSON 안에 담겨있는 books 배열만 뽑아내는 함수이다.
val bookList = books.map {mapper.treeToValue<Books>(it)};
bookList에 Books 객체 정보가 담긴다.