2017-08-10 89 views
0

我試圖反序列化所有字段都設置爲小寫的JSON。問題是:我的POJO對象的屬性設置爲camelcase,當我嘗試使用gson.fromJson反序列化時,我的camelcase屬性未設置。Gson反序列化小寫JSON到camelcase類對象

例JSON:

[ 
    { 
     "idpojo": 1, 
     "namepojo": "test" 
    } 
] 

POJO類:

public class Pojo { 

    private Integer idPojo; 
    private String namePojo; 

    //constructors, getters and setters 

} 

反序列化代碼:

List<T> objects = new ArrayList<>(); 
// At this point I only have an variable with a reference to a classe. Let's assume it is in fact a reference to Pojo class 
Class VARIABLE_WITH_REFERENCE_TO_A_CLASS = Pojo.class; 
Class pojoReference = VARIABLE_WITH_REFERENCE_TO_A_CLASS; 
String json = EXAMPLE_JSON_HERE; 
JSONArray jsonArray = new JSONArray(json); 
int len = jsonArray.length(); 
for (int i = 0; i < len; i++) { 
    objects.add((T) new Gson().fromJson(jsonArray.get(i).toString(), pojoReference))); 
} 

的原因,我反序列化JSON的泛型類的列表,而不是一個Pojo類的列表是因爲在我的代碼的這一點,我不知道什麼類我應該創建我的上校經文。

此代碼正常工作。問題是:反序列化後,Pojo類中的camelcase屬性未設置。

我到目前爲止所嘗試的一直在字段上使用@SerializedName註解,並且還創建了自定義的反序列化器,但是對於我來說也沒有辦法,因爲我真的不想/可以編寫特定的反序列化代碼對象。

問:

使用通用的,我怎麼能反序列化與小寫atributes JSON對象的Java類(如Pojo.class)與駝峯屬性?

回答

0

解決了使用Jackson而不是Gson進行反序列化的問題。

Jackson必須是2.5版或更高版本,還必須將映射器配置爲接受不區分大小寫的屬性。

新的工作代碼:

ObjectMapper mapper = new ObjectMapper(); 
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); 

List<T> objects = new ArrayList<>(); 
// At this point I only have an variable with a reference to a classe. Let's assume it is in fact a reference to Pojo class 
Class VARIABLE_WITH_REFERENCE_TO_A_CLASS = Pojo.class; 
Class pojoReference = VARIABLE_WITH_REFERENCE_TO_A_CLASS; 
String json = EXAMPLE_JSON_HERE; 
JSONArray jsonArray = new JSONArray(json); 
int len = jsonArray.length(); 
for (int i = 0; i < len; i++) { 
    objects.add(mapper.readValue(new JSONObject(json).toString(), pojoReference)); 
} 

感謝大家對你的時間!

1

fromJson()方法的文檔說,您將JSON反序列化爲的對象的類型不能是通用的。你可以指定一個類型並使用你提到的@SerializedName屬性來克服你的套接字不匹配的問題,但前提是你知道你從JSON創建的對象的類型。

+0

感謝輸入@Tyler,但我說,這不是我的選擇。 – Bonifacio