从改装响应中删除不需要的字符串
Remove unwanted string from retrofit response
我想从我的 retorfit2 POST 请求响应中删除字符串。
这是我的回复:
/*-secure-{"response":{"response":{"response":{"token":"95a2c5a8","email":"xxx@sample.in","name":"xxx"},"status":true,"code":0.0},"status":200},"status":200}*/
由于某些安全原因,我的服务器自动添加了字符串
/*-secure-
和 */
因为这个,在转换为 json 时,我低于 error:
com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 2 path $
Gson gson = new GsonBuilder()
.setLenient()
.build();
// ...
.addConverterFactory(GsonConverterFactory.create(gson)
请看this
我的自定义 gson 转换器 class
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();
}
}
}
我想从我的 retorfit2 POST 请求响应中删除字符串。
这是我的回复:
/*-secure-{"response":{"response":{"response":{"token":"95a2c5a8","email":"xxx@sample.in","name":"xxx"},"status":true,"code":0.0},"status":200},"status":200}*/
由于某些安全原因,我的服务器自动添加了字符串
/*-secure-
和 */
因为这个,在转换为 json 时,我低于 error:
com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 2 path $
Gson gson = new GsonBuilder()
.setLenient()
.build();
// ...
.addConverterFactory(GsonConverterFactory.create(gson)
请看this
我的自定义 gson 转换器 class
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();
}
}
}