用java将gson转换为object

时间:2012-08-21 22:44:25

标签: java json gson

我正在试图弄清楚如何使用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:Expected BEGIN_OBJECT但是STRING”错误。

1 个答案:

答案 0 :(得分:1)

你很亲密。您的对象需要具有名为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);
    }
}