Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep Letter Case in JSON Converter method in Groovy?

I'm trying to parse a groovy object to JSON. The properties names don't follow the correct camel case form.

class Client {
    String Name
    Date Birthdate
}

When I use this

Client client = new Client(Name: 'Richard Waters', Birthdate: new Date())
println (client as JSON).toString(true)

I got this

"client": {
      "name": 'Richard Waters',
      "birthdate": "2016-07-22T03:00:00Z",
}

How can I keep de Upper Case in start of my properties keys?

like image 872
ricardogobbo Avatar asked Jul 23 '16 18:07

ricardogobbo


People also ask

Does JSON have to be lowercase?

SQL, by default, is case insensitive to identifiers and keywords, but case sensitive to data. JSON is case sensitive to both field names and data.

Is Groovy JSON?

Groovy comes with integrated support for converting between Groovy objects and JSON. The classes dedicated to JSON serialisation and parsing are found in the groovy. json package.


1 Answers

Another option is to use a gson serializer with annotations: https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html

@Grab('com.google.code.gson:gson:2.7+')
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName

class Client {
    @SerializedName("Name")
    String name

    @SerializedName("Birthdate")
    Date birthdate
}

def client = new Client(name: 'John', birthdate: new Date())

def strJson = new Gson().toJson(client)
println strJson
like image 80
lospejos Avatar answered Oct 18 '22 00:10

lospejos