Convertendo JSONObject em objeto Java
Fiz uma chamada de descanso para um serviço e armazenei a resposta em umJSONObject
. No entanto, estou tentando convertê-lo em um objeto de classe e obtendo erros. Aqui está o meu código:
RestOperations operations = /*initalize*/;
String body = /*build request body*/;
String resourceResponse = operations.postForObject(/* url */, body, String.class);
JSONObject jsonResponse = new JSONObject(resourceResponse);
UserIdentifier userIdentifier = (UserIdentifier) jsonResponse.get("userIdentifier");
Aqui está a aparência da resposta:
{
"userIdentifier": {
"uid": "ee63a52cda7bf411dd8603ac196951aa77",
"code": "63a5297e7bf411dd8603ac196951aa77",
"retailId": "860658787",
"pointOfEntry": "RETAIL"
},
"resultCode": true
}
E aqui está o que oUserIdentifier
classe se parece com:
public class UserIdentifier {
private String uid;
private String code;
private String retailId;
public UserIdentifier() {
}
public UserIdentifier(String uid, String code, String retailId) {
this.uid = uid;
this.code = code;
this.retailId = retailId;
}
public String getuid() {
return uid;
}
public void setuid(String uid) {
this.uid = uid;
}
public String getcode() {
return code;
}
public void setcode(String code) {
this.code = code;
}
public String getretailId() {
return retailId;
}
public void setretailId(String retailId) {
this.retailId = retailId;
}
}
Mas eu recebo o erro:
java.lang.ClassCastException: org.json.JSONObject cannot be cast to app.identity.UserIdentifier
O que estou fazendo errado?
Editar 1: Aqui está a tentativa de usar o gson nas respostas:
Gson gson = new GsonBuilder().create();
String body = /*build request body*/;
String resourceResponse = operations.postForObject(/* url */, body, String.class);
JSONObject jsonResponse = new JSONObject(resourceResponse);
UserIdentifier userIdentifier = gson.fromJson(jsonResponse.getString("userIdentifier"), UserIdentifier.class);
Mas eu recebo o erro:
org.json.JSONException: JSONObject["userIdentifier"] not a string.
at org.json.JSONObject.getString(JSONObject.java:658) ~[json-20140107.jar:na]