如何解析json噴霧json使用蛇案(下劃線符號),而不是駱駝案?如何解析json與使用蛇情況(下劃線符號),而不是駱駝案例噴霧json
E.g.
case class Test(subjectDescription: String)
"{\"subject_description\":\"Medicine\"}".parseJson.convertTo[Test]
應該工作,而不是拋出異常。
如何解析json噴霧json使用蛇案(下劃線符號),而不是駱駝案?如何解析json與使用蛇情況(下劃線符號),而不是駱駝案例噴霧json
E.g.
case class Test(subjectDescription: String)
"{\"subject_description\":\"Medicine\"}".parseJson.convertTo[Test]
應該工作,而不是拋出異常。
此答案取自https://groups.google.com/forum/#!msg/spray-user/KsPIqWDK0AY/HcanflgRzMcJ。把它放在SO上,因爲SEO更好。
/**
* 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)
}
像這樣:
case class Test(subjectDescription: String)
implicit val testFormat = jsonFormat(Test.apply, "subject_description")
"{\"subject_description\":\"Medicine\"}".parseJson.convertTo[Test]
這裏的技巧是jsonFormat
函數使用字符串參數爲JSON對象鍵。
謝謝,但我更喜歡自動方法。我們有幾十個類,每個類都有幾十個字段。 – samthebest
def extractFieldNames()不會覆蓋任何內容......此處使用的spray-json的版本是什麼? –
@ÁkosVandraErm 1.3.1或更早版本。 – samthebest
耶確認此作品。我們實際上已經隱式導入了一個不相關的scalac bug。 –