[英]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.