简体   繁体   English

如何解析翻新JSON响应

[英]How to parse Retrofit JSON response

I have a typical Retrofit API request: 我有一个典型的Retrofit API请求:

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: 返回的JSON是:

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

How can I parse this JSON? 如何解析此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? 有更好的方法吗?

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()方法中应该看起来像这样

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

retrofit will parse the response and convert it to the class above. retrofit将解析响应并将其转换为上面的类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM