(我很新的GSON和JSON,所以請原諒我,如果這是一個愚蠢的問題)GSON轉換從JSON到Java對象
這裏是我的POST
請求response
:
String getResponse = ({"user_id":"1","device_id":"0","user_name":"jdoe","first_name":"John","last_name":"Doe"});
得到response
後,我用下面的方法把JSON
值進入我Java
對象:
FacebookUser facebookUser = new FacebookUser();
JSONObject responseObject = new JSONObject(getResponse);
Iterator<String> iter = responseObject.keys();
while (iter.hasNext()) {
String key = iter.next();
switch (key) {
case "user_id":
try {
Object value = responseObject.get(key);
facebookUser.setUserId((String) value);
} catch (JSONException e) {
Log.d("JsonException", "error" + e.toString());
}
break;
case "device_id":
try {
Object value = responseObject.get(key);
facebookUser.setDeviceId((String) value);
} catch (JSONException e) {
Log.d("JsonException", "error" + e.toString());
}
break;
case "user_name":
try {
Object value = responseObject.get(key);
facebookUser.setUsername((String) value);
} catch (JSONException e) {
Log.d("JsonException", "error" + e.toString());
}
break;
case "first_name":
try {
Object value = responseObject.get(key);
facebookUser.setFirstName((String) value);
} catch (JSONException e) {
Log.d("JsonException", "error" + e.toString());
}
break;
case "last_name":
try {
Object value = responseObject.get(key);
facebookUser.setLastName((String) value);
} catch (JSONException e) {
Log.d("JsonException", "error" + e.toString());
}
break;
}
}
這很好,所有的值都放在我的FacebookUser
對象中。但顯然這是非常繁瑣的工作,尤其是在我將得到帶有100個鍵/值對的response
的情況下。
所以我試着用Gson
,使這項工作一下子:
String getResponse = ({"user_id":"1","device_id":"0","user_name":"jdoe","first_name":"John","last_name":"Doe"});
FacebookUser facebookUser = new FacebookUser();
Gson gson = new GsonBuilder()
.disableHtmlEscaping()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.setPrettyPrinting()
.serializeNulls()
.create();
FacebookUser facebookUser = gson.fromJson(getResponse,
FacebookUser.class);
然而,所有的facebookUser
字段爲空...
是否有人可以幫忙嗎?
這裏是我FacebookUser類:
public class FacebookUser implements Serializable{
String userId;
String deviceId;
String username;
String firstName;
String lastName;
public FacebookUser() { //default ctor
}
... a bunch of getters
... a bunch of setters
}
您能不能告訴你FacebookUser類? –
我添加了FacebookUser類 – user2456977