将JSONObject转换为Java对象 [英] Converting JSONObject to Java Object

查看:3368
本文介绍了将JSONObject转换为Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对服务进行了休息调用,并将响应存储在 JSONObject 中。但是,我试图将其转换为类对象并获取错误。这是我的代码:

I made a rest call to a service and stored the response in a JSONObject. However, I am trying to convert it to a class object and getting errors. Here's my code:

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的尝试:

Edit 1: Here's the attempt at using gson from the answers:

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而不是获取字符串。以下是解决问题的方法:

Figured out what the problem was. Needed to extract the jsonobject instead of getting the string. Here was the line that fixed the issue:

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

这篇关于将JSONObject转换为Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆