简体   繁体   English

如何在 Groovy 中的 JSON 转换器方法中保留字母大小写?

[英]How to keep Letter Case in JSON Converter method in Groovy?

I'm trying to parse a groovy object to JSON.我正在尝试将 groovy 对象解析为 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?如何将 de Upper Case 保留在我的属性键的开头?

Another option is to use a gson serializer with annotations: https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html另一种选择是使用带有注释的gson serializerhttps : gson serializer

@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

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.因此,如果您想覆盖骆驼案例,一种选择是编写覆盖object.getProperties() aka object.properties自定义方法以返回自定义地图,因为在内部创建的地图使用MetaProperty.java类的getName()方法而不是而不是获得真实的财产名称。

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.然后,如果您将对象用作 JSON,它将返回预期的 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.在地图名称中,N 是大写的,在 json 中也是大写的。 Hope it helps!!希望有帮助!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM