将JSONObject转换为Java对象

我对服务进行了休息调用,并将响应存储在 JSONObject中.但是,我试图将其转换为类对象并获得错误.这是我的代码:
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");

这是响应的样子:

{
  "userIdentifier": {
    "uid": "ee63a52cda7bf411dd8603ac196951aa77","code": "63a5297e7bf411dd8603ac196951aa77","retailId": "860658787","pointOfEntry": "RETAIL"
  },"resultCode": true
}

这是UserIdentifier类的样子:

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;
    }
}

但我得到错误:

java.lang.ClassCastException: org.json.JSONObject cannot be cast to app.identity.UserIdentifier

我究竟做错了什么?

编辑1:这是尝试从答案中使用gson:

Gson gson = new GsonBuilder().create();
String body = /*build request body*/;
String resourceResponse = operations.postForObject(/* url */,String.class);
JSONObject jsonResponse = new JSONObject(resourceResponse);
UserIdentifier userIdentifier = gson.fromJson(jsonResponse.getString("userIdentifier"),UserIdentifier.class);

但我得到错误:

org.json.JSONException: JSONObject["userIdentifier"] not a string.
    at org.json.JSONObject.getString(JSONObject.java:658) ~[json-20140107.jar:na]
你可能需要使用gson
class Name{
String resultCode;
UserIdentifier useridentifier;
//getters

}

Gson gson=new Gson();
Name name=gson.fromJson(jsonString,Name.class);

相关文章

文章浏览阅读2.4k次。最近要优化cesium里的热力图效果,浏览...
文章浏览阅读1.2w次,点赞3次,收藏19次。在 Python中读取 j...
文章浏览阅读1.4k次。首字母缩略词 API 代表应用程序编程接口...
文章浏览阅读802次,点赞10次,收藏10次。解决一个JSON反序列...
文章浏览阅读882次。Unity Json和Xml的序列化和反序列化_uni...