Retrofit API响应中的空键

时间:2017-03-27 09:30:15

标签: android json api retrofit retrofit2

我一直在使用改造来进行API调用。我已经使用过很多次了,但现在我已经陷入困境了好几天了。会发生什么,我的API调用是成功的,但是包含列表的JSON密钥。我使用GSON和pojo类来解析和处理数据以供将来使用。 这是API响应: {
"IsBlockUser":"0", "BlockedByUserId":null, "BlockedMessage":null, "ChatHistory":[
{
"UserName":"Kunaal Satija", "UserId":"3", "UserImage":"3_80e16d23-6a72-46a4-b5c8-b67a78a3f8a2.jpg", "Message":"hi", "ChatReciverType":3, "RecieverId":"3", "CreatedDate":"12/13/2016 2:23:45 PM", "PrettyDate":"Dec 13,2016" }] }

这些是我用来解析响应的pojo类:GetChatHistoryResponse.java

public class GetChatHistoryResponse {

@SerializedName("IsBlockUser")
@Expose
private String isBlockUser;
@SerializedName("BlockedByUserId")
@Expose
private Object blockedByUserId;
@SerializedName("BlockedMessage")
@Expose
private Object blockedMessage;
@SerializedName("ChatHistory")
@Expose
private List<ChatHistory> chatHistory = null;

public String getIsBlockUser() {
    return isBlockUser;
}

public void setIsBlockUser(String isBlockUser) {
    this.isBlockUser = isBlockUser;
}

public Object getBlockedByUserId() {
    return blockedByUserId;
}

public void setBlockedByUserId(Object blockedByUserId) {
    this.blockedByUserId = blockedByUserId;
}

public Object getBlockedMessage() {
    return blockedMessage;
}

public void setBlockedMessage(Object blockedMessage) {
    this.blockedMessage = blockedMessage;
}

public List<ChatHistory> getChatHistory() {
    return chatHistory;
}

public void setChatHistory(List<ChatHistory> chatHistory) {
    this.chatHistory = chatHistory;
}}

和ChatHistory.java

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

public class ChatHistory {

@SerializedName("UserName")
@Expose
private String userName;
@SerializedName("UserId")
@Expose
private String userId;
@SerializedName("UserImage")
@Expose
private String userImage;
@SerializedName("Message")
@Expose
private String message;
@SerializedName("ChatReciverType")
@Expose
private Integer chatReciverType;
@SerializedName("RecieverId")
@Expose
private String recieverId;
@SerializedName("CreatedDate")
@Expose
private String createdDate;
@SerializedName("PrettyDate")
@Expose
private String prettyDate;

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getUserId() {
    return userId;
}

public void setUserId(String userId) {
    this.userId = userId;
}

public String getUserImage() {
    return userImage;
}

public void setUserImage(String userImage) {
    this.userImage = userImage;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public Integer getChatReciverType() {
    return chatReciverType;
}

public void setChatReciverType(Integer chatReciverType) {
    this.chatReciverType = chatReciverType;
}

public String getRecieverId() {
    return recieverId;
}

public void setRecieverId(String recieverId) {
    this.recieverId = recieverId;
}

public String getCreatedDate() {
    return createdDate;
}

public void setCreatedDate(String createdDate) {
    this.createdDate = createdDate;
}

public String getPrettyDate() {
    return prettyDate;
}

public void setPrettyDate(String prettyDate) {
    this.prettyDate = prettyDate;
}}

这是我使用的改造客户端:

    import com.edurev.Application;
import com.edurev.BuildConfig;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 *
 * Dated: 27-09-2016.
 */
public class RestClient {
    private static Retrofit retrofit = null;
    static Integer BKS_KEYSTORE_RAW_FILE_ID = 0;
    // Integer BKS_KEYSTORE_RAW_FILE_ID = R.raw.keystorebks;
    static Integer SSL_KEY_PASSWORD_STRING_ID = 0;
    //Integer SSL_KEY_PASSWORD_STRING_ID = R.string.sslKeyPassword;

    /**
     * @return
     */
    public static ApiInterface getApiInterface() {
        if (retrofit == null) {
            try {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BuildConfig.BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(httpClient().build())
                        //.client(secureConnection().build())
                        .build();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return retrofit.create(ApiInterface.class);
    }


    /**
     * @return
     */
    static Retrofit getRetrofitBuilder() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BuildConfig.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient().build())
                    .build();
        }
        return retrofit;
    }

    /**
     * @return
     */
    private static OkHttpClient.Builder httpClient() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        // set your desired log level
        //logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        if(BuildConfig.DEBUG)
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS);

        // add your other interceptors …
        // add logging as last interceptor
//        httpClient.addInterceptor(logging);
        return httpClient;
    }

    private static OkHttpClient.Builder secureConnection() throws
            KeyStoreException, CertificateException, NoSuchAlgorithmException,
            IOException, KeyManagementException {
        InputStream certificateInputStream = null;
        certificateInputStream = Application.mContext.getResources().openRawResource(BKS_KEYSTORE_RAW_FILE_ID);
        KeyStore trustStore = KeyStore.getInstance("BKS");
        try {
            trustStore.load(certificateInputStream, Application.mContext.getApplicationContext().getString(SSL_KEY_PASSWORD_STRING_ID).toCharArray());
        } finally {
            certificateInputStream.close();
        }
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(trustStore);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);

        /*

        retrofit 1.9.x

        OkHttpClient client = new OkHttpClient();

        client.setSslSocketFactory(sslContext.getSocketFactory());

        client.setWriteTimeout(15, TimeUnit.MINUTES);

        client.setConnectTimeout(15, TimeUnit.MINUTES); // connect

        timeout

        client.setReadTimeout(15, TimeUnit.MINUTES);

        return new OkClient(client);*/

        //Retrofit 2.0.x

        TrustManager[] trustManagers = tmf.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
        }
        X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient.Builder client3 = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory, trustManager);
        return client3;
    }
}

这是我使用的API接口方法和调用方法:

`@FormUrlEncoded
 @POST("Chat_GetChatHistory")
 Call<GetChatHistoryResponse> getChatHistory(@FieldMap HashMap<String, String> map);

RestClient.getApiInterface().getChatHistory(mCommonParams.getMap()).enqueue(new Callback<GetChatHistoryResponse>() {
        @Override
        public void onResponse(Call<GetChatHistoryResponse> call, Response<GetChatHistoryResponse> response) {

        }

        @Override
        public void onFailure(Call<GetChatHistoryResponse> call, Throwable t) {

        }
    });

`

现在我收到的API响应中的ChatHistory列表为空,但其他键返回正常。我尝试使用ResponseBody数据类型,以便在出现任何解析错误时跳过解析。但是,当我使用Web界面调用API时,结果很好,因为我似乎无法发现问题。 这是一个调试器响应,ResponseBody设置为API接口中的数据类型:[size = 81 text = {“IsBlockUser”:“0”,“BlockedByUserId”:null,“BlockedMessage”:null,...]

任何帮助将不胜感激!

0 个答案:

没有答案