Reading snake_case attributes as camelCase in Play Json
Asked Answered
U

4

17

I want to extract json as a case class within Play application. The attributes in case class are defined in camelCase and json data comes in snake_case.

case class User(userId: Long, userName: String)

and json would be like this {"user_name":"Vishal","user_id":67}

Is there an easy way to instruct play json to automatically do the mapping and extract, like providing some annotations etc.

Undecided answered 13/8, 2013 at 6:19 Comment(0)
H
16

This is a quite old question, but I didn't find any answer for it, so I went to the Play JSON Github repository and found this:

implicit val config = JsonConfiguration(SnakeCase)

implicit val userReads: Reads[PlayUser] = Json.reads[PlayUser]

So, now seems that exists an official way of doing this

https://github.com/playframework/playframework/blob/d96d42e4baa2261d0e0a9c36518f6921e247e402/documentation/manual/working/scalaGuide/main/json/code/ScalaJsonAutomatedSpec.scala#L128

Hispanic answered 21/10, 2016 at 9:57 Comment(2)
This is really useful but is available only in the upcoming 2.6 release. Expected April-May 2017.Scag
this is the good way to do it now, this should be the approuved answerInjector
H
1

See @GlauberCampinho's answer for the official solution for this issue,
which didn't exist at the time of writing there this answer.


Play uses Jackson. In Java, you can use the Jackson annotation org.codehaus.jackson.annotate.JsonProperty on your properties to set the names manually. The argument for the value parameter will be used as the key's name.

@JsonProperty("user_name")
String userName;

I don't know if this also works in Play using Scala. Based on the comments in this thread about Scala and Jackson the syntax for deserialisation should be something like this:

class User @JsonCreator()( @JsonProperty("user_id") val userId:Long, @JsonProperty("user_name") val userName:String )

You can find another example of Jackson annotations in a case class in this question.

Hellkite answered 13/8, 2013 at 13:9 Comment(1)
Jackson @JsonProperty doesn't work with Play Macros. So if you use Json.format[User] you should look for @GlauberCampinho answerInjector
H
1

If you're using Play 2's JSON Inception, then No. If you're not, then you can just use the @JsonProperty annotations.

I was trying to get this to work with JSON Inception for a few days using various forms and configurations of jerkson/jackson annotations with no such luck!

Hop answered 26/8, 2013 at 3:6 Comment(0)
T
0

For Play Json 2.x: https://github.com/tototoshi/play-json-naming

This seems to satisfy exactly what I'm looking for, hopefully it helps!

Triturable answered 22/6, 2016 at 15:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.