简体   繁体   English

在翻新中解析Json响应

[英]parse Json response in retrofit

The response of the call from WebService is as follows: 来自WebService的调用响应如下:

{
    "mobilenumber": "09999999999", 
    "service": "1" , 
    "id": "1"
}

How do I parse received Json into objects? 如何将收到的Json解析为对象?

@Override
public void onResponse(Call<Login> call, Response<Login> response) {

    if (response.isSuccessful()) {

    } 
}

This code gives you how to parse the json. 此代码为您提供了如何解析json的信息。

    @Override
    public void onResponse(Call<Login> call, Response<Login> response) {
     if (response.isSuccessful()) {
       JSONObject jsonobject = new JSONObject(yourresponse);
       String mobilenumber = jsonobject.getString("mobilenumber");
       String service = jsonobject.getString("service");
       String id = jsonobject.getString("id");
            } 

By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody type. 默认情况下,Retrofit只能将HTTP正文反序列化为OkHttp的ResponseBody类型。

A Converter which uses Gson for serialization to and from JSON. 一个使用Gson来往于JSON的序列化的Converter。 A default Gson instance will be created or one can be configured and passed to the GsonConverterFactory to further control the serialization. 将创建一个默认的Gson实例,或者可以配置一个实例,并将其传递给GsonConverterFactory以进一步控制序列化。

Add to gradle; 添加到gradle;

compile 'com.squareup.retrofit2:converter-gson:latest.version'


Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.xxx.com")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

Assuming you have a Login model like this: 假设您具有这样的Login模型:

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Login {

    @SerializedName("mobilenumber")
    @Expose
    private String mobilenumber;

    @SerializedName("service")
    @Expose
    private String service;

    @SerializedName("id")
    @Expose
    private String id;

    public String getMobilenumber() {
        return mobilenumber;
    }

    public void setMobilenumber(String mobilenumber) {
        this.mobilenumber = mobilenumber;
    }

    public String getService() {
        return service;
    }

    public void setService(String service) {
        this.service = service;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

In your retrofit onResponse() method: 在改造onResponse()方法中:

@Override
public void onResponse(Call<Login> call, Response<Login> response) {

    if (response.isSuccessful()) {

        Login loginObject = response.body();

        String mobileNumber = loginObject.getMobilenumber();
        String service = loginObject.getService();
        String id = loginObject.getId();
    } 
}

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

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