scala에서 json4s를 간단하게 사용할 때, Map[String, Any]으로 파싱할 때 특별히 에러가 발생하지 않는다.


간단히 동작하는 예시는 다음과 같다. 



import
org.json4s._
import org.json4s.JsonAST.{JObject, JValue}
import org.json4s.jackson.{Json, JsonMethods}

implicit val formats = DefaultFormats
val source = """{"comment_type":"general"}"""
val commentType = JsonMethods.parse(source) .extract[Map[String, Any]].get("comment_type")
println(commentType)



하지만, Spark에서 사용하면 에러가 발생한다. 


org.json4s.package$MappingException: No usable value for... 




이런 비슷한 얘기가 json4s 이슈에 있다. 

https://github.com/json4s/json4s/issues/124




그래서 Map이 아닌 case class를 사용하면 또 에러가 발생한다. 


기본 값을 넣어줘야 에러가 발생하지 않는다. 



case class Comment(comment_type: String = "general")


좀 더 고급스럽게 Option을 추가한다.


case class Comment(comment_type: Option[String] = Some("general"))



 잘 동작한다. Map 대신 case class를 사용하기를 추천한다. 


import org.json4s._
import org.json4s.JsonAST.{JObject, JValue}
import org.json4s.jackson.{Json, JsonMethods}

case class Comment(comment_type: Option[String] = Some("general"))

implicit val formats = DefaultFormats
val source = """{"comment_type":"general"}"""
val commentType = JsonMethods.parse(source).extract[Comment].comment_type
println(commentType)



Spark에서 이렇게 쓰면 아주 잘 작동할 것 같았지만, 이슈가 있다. 다른 필드 파싱할 때, 예상되는 타입과 실제 값과의 차이로 파싱 에러가 발생할 수 있다.



이럴 때는 Try문를 추가하고, Comment에 해당되는 모든 필드에 대해서 Option 처리를 추가해야 한다. 어떤 값과 상관없이 처리할 수 있도록 해야 한다.


case class Comment(comment_type: Option[String] = Some("general"), action: Option[String] = Some("create", ....)

Posted by '김용환'
,