JSON to Scala class with GSON - SerializedName annotation does not work

975 views
Skip to first unread message

Tim

unread,
Mar 5, 2013, 9:33:57 AM3/5/13
to scala...@googlegroups.com
I have a simple Scala class:

import com.google.gson.annotations.SerializedName
class MyTest(@SerializedName("my_test") var myTest: String) 
    extends Serializable { ... }

And I have this code:

val testJson = "{\"myTest\": \"my-test\"}"
val myTest = gson.fromJson(testJson, classOf[MyTest])

This works fine! The content of the variable of myTest is my-test.

In reality, my JSON looks like this:

val testJsonWithUnderscore = "{\"my_test\": \"my-test\"}"
val myTest = gson.fromJson(testJsonWithUnderscore, classOf[MyTest])

So, the variable name myTest does not match with the my_test of the JSON string. So I included @SerializedName("my_test") but it does not work. The var myTest is null.

The @SerializedName("my_test") does not work like expected. What is wrong here?

Shail Mehta

unread,
Aug 12, 2013, 12:36:23 PM8/12/13
to scala...@googlegroups.com
Hi Tim -
I have exactly the same issue.  Were you able to find a resolution?

thanks

eh...@gigya-inc.com

unread,
Aug 2, 2016, 1:01:10 PM8/2/16
to scala-user
You can just add it as var in body for example:

class MyTest(){
@SerializedName("my_test") 
 var myTest: String = null

Gigya | The Leader in Customer Identity Management
2016 CRM Watchlist 
Winner

Raul Bache

unread,
Aug 3, 2016, 7:45:48 AM8/3/16
to scala-user
Reply all
Reply to author
Forward
0 new messages