0
votes

Sample Json:

var testString = {"eventType":"REQUEST","event-id":"6e904afa-62e8-40fb-8c6a-66a2ba21a3e1"}

Scala case class:

case class EventHeader(eventType:String,event-id:String)

De-serialization code:

var header = new Gson().fromJson(testString,classOf[EventHeader])

Resulting in following error (because of special character in "event-id" field name):

:1: error: ':' expected but identifier found. case class EventHeader(eventType:String,event-id:String)

In Java we can have an annotation on "event-id" field and name it as "eventId" or "id".

Is there a similar way in Scala?

3

3 Answers

2
votes
scala> case class EventHeader(eventType:String,`event-id`:String)
defined class EventHeader

scala> EventHeader("some event", "eventid")
res1: EventHeader = EventHeader(some event,eventid)

Note the quote around event-id in the case class declaration

2
votes
import com.fasterxml.jackson.annotation._
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule

case class EventHeader(@JsonProperty("event-id") eventId: String,@JsonProperty("eventType") eventType:String)

val mapper = new ObjectMapper                    
mapper.registerModule(DefaultScalaModule)         
val obj = mapper.readValue("""{"eventType":"REQUEST","event-id":"6e904afa-62e8-40fb-8c6a-66a2ba21a3e1"}""", classOf[EventHeader])
0
votes

Using Gson

 import com.google.gson.Gson

 case class Request(command_type: String, sub_commands: 
 java.util.ArrayList[Command])

 new Gson().toJson(new Request("Command", subCommands))