diff options
author | Jakob Odersky <jakob@odersky.com> | 2018-04-19 15:46:48 -0700 |
---|---|---|
committer | Jakob Odersky <jakob@odersky.com> | 2018-04-19 16:36:31 -0700 |
commit | 3c00a1ad8013c375a598dd88139dce174e9bf401 (patch) | |
tree | 0d8f77cf46ddb6c1100ec0ff76ff6dc0b26fedd6 /shared/src/test/scala | |
parent | 83942244b48d8f7a68ecdaade90b92a79378d43c (diff) | |
download | spray-json-derivation-3c00a1ad8013c375a598dd88139dce174e9bf401.tar.gz spray-json-derivation-3c00a1ad8013c375a598dd88139dce174e9bf401.tar.bz2 spray-json-derivation-3c00a1ad8013c375a598dd88139dce174e9bf401.zip |
Expose functionality to override parameter to field name mapping
Diffstat (limited to 'shared/src/test/scala')
-rw-r--r-- | shared/src/test/scala/FieldNameTests.scala | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/shared/src/test/scala/FieldNameTests.scala b/shared/src/test/scala/FieldNameTests.scala new file mode 100644 index 0000000..f1b76a9 --- /dev/null +++ b/shared/src/test/scala/FieldNameTests.scala @@ -0,0 +1,72 @@ +package spray.json + +import org.scalatest._ + +trait SnakeCaseFormats { self: DerivedFormats => + override def extractFieldName(paramName: String) = + FieldNaming.substituteCamel(paramName, '_') +} +trait KebabCaseFormats { self: DerivedFormats => + override def extractFieldName(paramName: String) = + FieldNaming.substituteCamel(paramName, '-') +} + +object FieldNaming { + + @inline final private def isLower(ch: Char): Boolean = + ((ch & 0x20) != 0) || (ch == '_') + + @inline def substituteCamel(paramName: String, substitute: Char) = { + val length = paramName.length + val builder = new StringBuilder(length) + var i = 0 + while (i < length) { + val cur = paramName(i) + if (isLower(cur) && i + 1 < length) { + builder.append(cur) + val next = paramName(i + 1) + if (!isLower(next)) { + builder.append(substitute) + builder.append((next ^ 0x20).toChar) + } else { + builder.append(next) + } + i += 1 + } else { + builder.append((cur ^ 0x20).toChar) + } + i += 1 + } + builder.result() + } + +} + +class FieldNameTests extends FlatSpec with FormatTests { + + case class A(camelCASE: String, `__a_aB__`: Int, `a-a_B`: Int) + case class B(camelCaseA: A) + + trait All extends DefaultJsonProtocol with DerivedFormats { + implicit val bFormat = jsonFormat[B] + } + + { + object Protocol extends All with SnakeCaseFormats + import Protocol._ + "snake_case" should behave like checkRoundtrip( + B(A("helloWorld", 0, 0)), + """{"camel_case_a":{"camel_case":"helloWorld","__a_a_b__":0,"a-a_b":0}}""" + ) + } + + { + object Protocol extends All with KebabCaseFormats + import Protocol._ + "kebab-case" should behave like checkRoundtrip( + B(A("helloWorld", 0, 0)), + """{"camel-case-a":{"camel-case":"helloWorld","__a_a-b__":0,"a-a_b":0}}""" + ) + } + +} |