ricardogobbo
ricardogobbo

Reputation: 1740

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?

Upvotes: 7

Views: 2410

Answers (2)

lospejos
lospejos

Reputation: 1986

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

Upvotes: 3

Vinay Prajapati
Vinay Prajapati

Reputation: 7514

Well you are breaking standard naming convention and hence it automatically converts it to camel case.

Hence, if you want to override the camel case, one option is write your custom method that overrides object.getProperties() aka object.properties to return a custom map as internally the map created uses getName() method of MetaProperty.java class rather than getting the real property name.

Hence, the only job you have to perform is to write a custom generic method that converts your object to map.

And then if you use object as JSON it will return expected json.

For example

class Client {
    String name
}

Client client = new Client(name: 'Richard Waters')
println (["Name":"test"] as grails.converters.JSON)

Here in map Name's N is capital and is returned capital in json too. Hope it helps!!

Upvotes: -1

Related Questions