How to parse json with spray json that uses snake case (underscore notation) instead of camel case

牧云@^-^@ 提交于 2019-12-23 02:39:48

问题


How to parse json with spray json that uses snake case (underscore notation) instead of camel case?

E.g.

case class Test(subjectDescription: String)
"{\"subject_description\":\"Medicine\"}".parseJson.convertTo[Test]

should work and not throw exception.


回答1:


Like this:

case class Test(subjectDescription: String)
implicit val testFormat = jsonFormat(Test.apply, "subject_description")
"{\"subject_description\":\"Medicine\"}".parseJson.convertTo[Test]

The trick here is jsonFormat function takes string arguments for json object keys.




回答2:


This answer is taken from https://groups.google.com/forum/#!msg/spray-user/KsPIqWDK0AY/HcanflgRzMcJ. Putting it on SO since the SEO is better.

/**
 * A custom version of the Spray DefaultJsonProtocol with a modified field naming strategy
 */
trait SnakifiedSprayJsonSupport extends DefaultJsonProtocol {
  import reflect._

  /**
   * This is the most important piece of code in this object!
   * It overrides the default naming scheme used by spray-json and replaces it with a scheme that turns camelcased
   * names into snakified names (i.e. using underscores as word separators).
   */
  override protected def extractFieldNames(classTag: ClassTag[_]) = {
    import java.util.Locale

    def snakify(name: String) = PASS2.replaceAllIn(PASS1.replaceAllIn(name, REPLACEMENT), REPLACEMENT).toLowerCase(Locale.US)

    super.extractFieldNames(classTag).map { snakify(_) }
  }

  private val PASS1 = """([A-Z]+)([A-Z][a-z])""".r
  private val PASS2 = """([a-z\d])([A-Z])""".r
  private val REPLACEMENT = "$1_$2"
}

object SnakifiedSprayJsonSupport extends SnakifiedSprayJsonSupport

import SnakifiedSprayJsonSupport._

object MyJsonProtocol extends SnakifiedSprayJsonSupport {
  implicit val testFormat = jsonFormat1(Test.apply)
}


来源:https://stackoverflow.com/questions/33367983/how-to-parse-json-with-spray-json-that-uses-snake-case-underscore-notation-ins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!