How to parse Retrofit JSON response

纵饮孤独 提交于 2020-01-22 17:08:10

问题


I have a typical Retrofit API request:

RestAdapter restAdapter = new RestAdapter.Builder()
        .setEndpoint(URL)
        .build();

ApiEndpointInterface api = restAdapter.create(ApiEndpointInterface.class);

api.getToken('1', new Callback<DefaultResponse>() {
    @Override
    public void success(DefaultResponse json, Response response) {
        //
    }

    @Override
    public void failure(RetrofitError response) {
        //
    }
});

And the returned JSON is:

{"success":true,"data":{"token_id":"pPt9AKl0Cg","token_key":"8ax224sFrJZZkStAQuER"}}

How can I parse this JSON? It seems wrong/tedious to create a new model class for each different response across my app. Is there a better way to do it?


回答1:


you should write your model class like below

public class MyResponseModel {//write setters and getters.
        private boolean success;
        private DataModel data;

    public static class DataModel {
        private String token_id;
        private String token_key;
    }
}

now in your getToken() method should look like this

getToken('1', Callback<MyResponseModel> response);

retrofit will parse the response and convert it to the class above.




回答2:


Try this code,

JsonElement je = new JsonParser().parse(s);
JsonObject asJsonObject = je.getAsJsonObject();
JsonElement get = asJsonObject.get("data");
System.out.println(s + "\n" + get);
JsonObject asJsonObject1 = get.getAsJsonObject();
JsonElement get1 = asJsonObject1.get("token_id");
System.out.println(get1);
JsonElement get2 = asJsonObject1.get("token_key");
System.out.println(get2);


来源:https://stackoverflow.com/questions/33338923/how-to-parse-retrofit-json-response

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