2015-12-14 60 views
0

我有一個Java類對象:將Java對象轉換爲JSON字符串

class TempClass { 
@Expose 
String errorCode 
@Expose 
String message 
String name 
String cause 

TempClass(String errorCode, String message) { 
    this.errorCode = errorCode 
    this.message = message 
    } 
} 

我能夠使用GSON罐子

TempClass t = new TempClass("404","page not found") 
GsonBuilder builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() 
String json = builder.create().toJson(t); 

JSON字符串我正在給對象轉換成JSON是

{ errorCode:「404」, message:「page not found」 }

但我要的是:

「TempClass」{ 錯誤碼: 「404」, 消息: 「找不到網頁」 }

或更好,如果有任何其他複雜的方式,我可以將「tempClass」(或任何其他屬性)映射到其他屬性。

回答

0

你可以嘗試創建一個地圖,其中「tempClass」是關鍵,你TempClass對象的價值,就像這樣:

TempClass t = new TempClass("404","page not found") 
Map<String, Object> map = new Hashmap<String, Object>(); 
map.put("tempClass", t); 
GsonBuilder builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() 
String json = builder.create().toJson(map); 

這是一種方便,快捷的方式,以達到你所需要的由於Google地圖是由Gson開箱分析的,但要小心:如果您有更多像這樣的屬性,最好爲此創建一個新類別