Converting JSONObject to Java Object

馋奶兔 提交于 2019-11-29 04:26:41

You may need use gson

   class Name{
String resultCode;
UserIdentifier useridentifier;
//getters

}

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

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

the things is that you can't cast the object that return in the get method like this, One solution could be this, using GSON library:

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

Use Gson library

Gson gson=new GsonBuilder().create();

UserIdentifier userIdentifier=gson.fromJson(jsonString,UserIdentifier.class);

In your case jsonString is resourceResponse

For details study Gson documentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!