2

gsonを使用してredditのAPI応答を使用可能なフォームに変換する方法を理解しようとしています。いくつかのコードの後、私は使用します

System.out.println(response.toString());

出力を取得するには(少し編集)

{"json": {"errors": [], "data": {"modhash": "dosiom5o6abbbb758729039f04762a05778db4aeeeacd8eb4a", "cookie": "14756159,2012-08-21T12:05:05,0971bdec35d71af4073cf56ad82fb0ae7c5fe2d1"}}}

グーグルした後、次のクラスを作成しました

class GSONClass {

    private Response jsonresponse;

    public Response getJsonresponse() {
        return jsonresponse;
    }

    public void setJsonresponse(Response jsonresponse) {
        this.jsonresponse = jsonresponse;
    }

    public static class Response {
        private String[] errors;
        private Data data;

        public Data getData() {
            return data;
        }

        public void setData(Data data) {
            this.data = data;
        }

        public String[] getErrors() {
            return errors;
        }

        public void setErrors(String[] errors) {
            this.errors = errors;
        }
    }

    public static class Data {
        private String modhash = "hi";
        private String cookie;

        public String getCookie() {
            return cookie;
        }

        public void setCookie(String cookie) {
            this.cookie = cookie;
        }

        public String getModhash() {
            return modhash;
        }

        public void setModhash(String modhash) {
            this.modhash = modhash;
        }
    }
}

それから私は使用します:

GSONClass target = new GSONClass();
String json = gson.toJson(response.toString());
GSONClass target = gson.fromJson(json, GSONClass.class);

「java.lang.IllegalStateException:BEGIN_OBJECTが必要ですが、STRINGでした」というエラーが発生するため、何か問題が発生しています。

4

1 に答える 1

1

あなたは近かった。オブジェクトには、array(errors)を含むjsonという名前の属性と、プロパティmodhashとcookieを含むdataという名前のオブジェクトが必要でした。jsonResponseと呼んでいたプロパティは、jsonと呼ばれる必要がありました。

public class GSONClass {
    private Response json;

    public static class Response {
        private String[] errors;
        private Data data;
    }

    public static class Data {
        private String modhash = "hi";
        private String cookie;
    }
}

そしてスタブ/ランナー。

import com.google.gson.Gson;

public class Main {

    public static void main(String[] args) {
        String response = "{\"json\": {\"errors\": [], \"data\": {\"modhash\": \"dosiom5o6abbbb758729039f04762a05778db4aeeeacd8eb4a\", \"cookie\": \"14756159,2012-08-21T12:05:05,0971bdec35d71af4073cf56ad82fb0ae7c5fe2d1\"}}}";
        GSONClass target = new Gson().fromJson(response, GSONClass.class);
        System.out.println(target);
    }
}
于 2012-08-22T01:40:12.600 に答える