[英]How to keep Letter Case in JSON Converter method in Groovy?
我正在尝试将 groovy 对象解析为 JSON。 属性名称不遵循正确的驼峰式格式。
class Client {
String Name
Date Birthdate
}
当我使用这个
Client client = new Client(Name: 'Richard Waters', Birthdate: new Date())
println (client as JSON).toString(true)
我得到了这个
"client": {
"name": 'Richard Waters',
"birthdate": "2016-07-22T03:00:00Z",
}
如何将 de Upper Case 保留在我的属性键的开头?
另一种选择是使用带有注释的gson serializer
: https : 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
好吧,您违反了标准命名约定,因此它会自动将其转换为驼峰式大小写。
因此,如果您想覆盖骆驼案例,一种选择是编写覆盖object.getProperties()
aka object.properties
自定义方法以返回自定义地图,因为在内部创建的地图使用MetaProperty.java
类的getName()
方法而不是而不是获得真实的财产名称。
因此,您必须执行的唯一工作是编写一个自定义泛型方法,将您的对象转换为映射。
然后,如果您将对象用作 JSON,它将返回预期的 json。
例如
class Client {
String name
}
Client client = new Client(name: 'Richard Waters')
println (["Name":"test"] as grails.converters.JSON)
在地图名称中,N 是大写的,在 json 中也是大写的。 希望有帮助!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.