如何使用使用蛇案(下划线表示法)而不是骆驼案的Spray JSON解析JSON [英] How to parse json with spray json that uses snake case (underscore notation) instead of camel case
本文介绍了如何使用使用蛇案(下划线表示法)而不是骆驼案的Spray JSON解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用使用蛇形(下划线表示法)而不是驼峰式的spray json解析json?
How to parse json with spray json that uses snake case (underscore notation) instead of camel case?
例如
case class Test(subjectDescription: String)
"{\"subject_description\":\"Medicine\"}".parseJson.convertTo[Test]
应该工作,并且不会引发异常.
should work and not throw exception.
推荐答案
此答案来自 https://groups.google.com/forum/#!msg/spray-user/KsPIqWDK0AY/HcanflgRzMcJ .由于SEO更好,因此将其放在SO上.
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)
}
这篇关于如何使用使用蛇案(下划线表示法)而不是骆驼案的Spray JSON解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文