当前位置: 首页 > 面试题库 >

将JSONObject转换为Java对象

吕越彬
2023-03-14
问题内容

我对服务进行了调用,并将响应存储在中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 */, body, 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]

问题答案:

找出问题所在。需要提取jsonobject而不是获取字符串。这是解决此问题的行:

UserIdentifier userIdentifier = gson.fromJson(jsonResponse.getJSONObject("userIdentifier").toString(), UserIdentifier.class);


 类似资料:
  • 问题内容: 我想将elasticsearch搜索结果转换为Json Object。我还没有找到任何直接转换的正确方法。 有什么方法可以将ElasticSearch响应转换为Json对象吗? 问题答案: 在Java中,您可以直接将SearchResponse转换为JSONObject。以下是方便的代码。

  • 我想将以下字符串作为json发布到服务器。 {“FirstName”:“John”,“LastName”:“Smith”},{“FirstName”:“John”,“LastName”:“Smith”} 但是如果我使用下面的代码,我会得到json对象的数组列表。 输出: [{"FirstName":"John","LastName":"Smith" }, { "FirstName":"John",

  • 问题内容: 我有一个对象。用它创建对象的最简单方法是什么? 问题答案: 再次从中获取JSON字符串并进行解析

  • 问题内容: 我有一些要转换成的属性 我可以从json.org或使用什么吗? 问题答案: 使用来自http://json.org/的 Jackson(http://jackson.codehaus.org/)

  • 我想将字节转换为JsonObject。我试着这样: 但我遇到编译器错误: 我怎么能这样呢?

  • 问题内容: 我正在使用A 将Json从Web转换为字符串。 这可能很简单,但是我似乎无法将此字符串转换为。 我怎样才能做到这一点? 问题答案: 请参阅文档和示例。