Reading snake_case attributes as camelCase in Play Json

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

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

and json will look like this: {"Username": "Wrote", "User_ID": 67}

Is there an easy way to instruct play json to automatically render and retrieve, such as provide some annotations, etc.

+8
playframework
source share
4 answers

This probably won't work right away, so maybe you should think about other solutions, such as finding an additional library to handle this.

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

 @JsonProperty("user_name") String userName; 

I do not know if this works on Play using Scala. Based on the comments in this thread about Scala and Jackson , the deserialization syntax 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 the case class in this question .

+1
source share

If you are using Play 2 JSON Inception, then None. If you do not, you can simply use @JsonProperty annotations.

I tried to get this to work with JSON Inception for several days using various forms and jerkson / jackson annotation configurations without such luck!

+1
source share

This is a pretty old question, but I did not 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 it seems that there is an official way to do this

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

+1
source share

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

This is similar to what I'm exactly looking for, hope it helps!

0
source share

All Articles