복붙노트

[SPRING] JSONObject를 Java 객체로 변환하기

SPRING

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 */, 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]

해결법

  1. ==============================

    1.gson을 사용해야 할 수도 있습니다.

    gson을 사용해야 할 수도 있습니다.

       class Name{
    String resultCode;
    UserIdentifier useridentifier;
    //getters
    
    }
    
    Gson gson=new Gson();
    Name name=gson.fromJson(jsonString,Name.class);
    
  2. ==============================

    2.문제가 무엇인지 알아 냈습니다. 문자열을 가져 오는 대신 jsonobject를 추출해야했습니다. 문제를 해결 한 선이있었습니다.

    문제가 무엇인지 알아 냈습니다. 문자열을 가져 오는 대신 jsonobject를 추출해야했습니다. 문제를 해결 한 선이있었습니다.

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

    3.Gson 라이브러리 사용

    Gson 라이브러리 사용

    Gson gson=new GsonBuilder().create();
    
    UserIdentifier userIdentifier=gson.fromJson(jsonString,UserIdentifier.class);
    

    귀하의 경우 jsonString은 resourceResponse입니다.

    자세한 내용은 Gson 문서를 참조하십시오.

  4. ==============================

    4.것은 이것과 같은 get 메소드에서 반환하는 객체를 캐스트 할 수 없다는 것입니다. GSON 라이브러리를 사용하는 한 가지 해결책은 다음과 같습니다.

    것은 이것과 같은 get 메소드에서 반환하는 객체를 캐스트 할 수 없다는 것입니다. GSON 라이브러리를 사용하는 한 가지 해결책은 다음과 같습니다.

    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);
    
  5. from https://stackoverflow.com/questions/35210070/converting-jsonobject-to-java-object by cc-by-sa and MIT license