从改装响应中删除不需要的字符串

时间:2017-01-19 15:31:22

标签: android json exception response retrofit2

我想从retorfit2 POST请求响应中删除字符串。

这是我的回复

MPI_Allgather(&c, 1, MPI_LONG, &oldcount, 1, MPI_LONG, MPI_COMM_WORLD);

由于某些安全原因,我的服务器会自动添加字符串

/*-secure-{"response":{"response":{"response":{"token":"95a2c5a8","email":"xxx@sample.in","name":"xxx"},"status":true,"code":0.0},"status":200},"status":200}*/ /*-secure-

由于这一点,在转换为json时,我遇到错误

*/

2 个答案:

答案 0 :(得分:2)

我的自定义gson转换器类

    final class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;
    private Pattern pattern = Pattern.compile("^\\/\\*-secure-\\W(.*)\\*\\/$");

    CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        System.out.println(response);
        Matcher matcher = pattern.matcher(response);

        JsonReader jsonReader = gson.newJsonReader(new StringReader(matcher.group(1)));
        try {
            return adapter.read(jsonReader);
        } finally {
            value.close();
        }
    }
}

答案 1 :(得分:1)

{{1}}

请参阅this