后台某个接口返回的数据结构如下所示
{
"status":"0",
"content":[
{
"id":"23",
"headpic":"[http://newapp.com/4ddaadae-a0d0-4de3-9ecf-d547db9f6099](http://newapp.myqcloud.com/4ddaadae-a0d0-4de3-9ecf-d547db9f6099)",
"accountid":"6324",
"card_id":"6089",
"sex":"1",
"nickname":"农民的儿子",
"reply":{
"id":"4134",
"fid":"4006",
"user_id":"6324",
"card_id":"0",
"farm_id":"3813",
"text":"谢谢评价",//回复内容
"trendsid":"2743",
"time":"1553670844"//回复时间
"read":"0",
"ztime":null,
"status":"1"
}
}
]
}
但是实际返回时,若reply为空字符串,返回的数据如下
{
"content": [
{
"accountid": "12196",
"card_id": "22786",
"ctime": "1547632828",
"headpic": "http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIsicgDhYpVw5P3yYT88A4BaWTiaa7euaBTktq8icjYER0TrJGj2VHsA1d48Z313jfa8KDyD09m0wdBg/132",
"id": "4085",
"nickname": "?",
"reply": ""
}
],
"status": "0"
}
此时数据解析时就会出错
需要写一个typeAdapter(如下) 设置到Bean类里
public class ReplyEmptyAdapter extends TypeAdapter<CommentBean.ReplyBean> {
private TypeAdapter< CommentBean.ReplyBean> mTypeAdapter;
@Override
public void write(JsonWriter out, CommentBean.ReplyBean value) throws IOException {
initAdapter();
mTypeAdapter.write(out,value);
}
@Override
public CommentBean.ReplyBean read(JsonReader in) throws IOException {
JsonToken peek = in.peek();
if (peek == JsonToken.NULL || peek == JsonToken.STRING) {
in.skipValue();
return null;
}
initAdapter();
CommentBean.ReplyBean v = mTypeAdapter.read(in);
return v;
}
private void initAdapter() {
if (mTypeAdapter==null) {
ConstructorConstructor constructorConstructor = new ConstructorConstructor(Collections.<Type, InstanceCreator<?>>emptyMap());
JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory = new JsonAdapterAnnotationTypeAdapterFactory(constructorConstructor);
ReflectiveTypeAdapterFactory factory = new ReflectiveTypeAdapterFactory(
constructorConstructor, FieldNamingPolicy.IDENTITY, Excluder.DEFAULT, jsonAdapterFactory);
mTypeAdapter = factory.create(new Gson(), new TypeToken< CommentBean.ReplyBean>() {
});
}
}
}
bean类的对应字段如下所示
@JsonAdapter(value = ReplyEmptyAdapter.class)
@SerializedName("reply")
private ReplyBean mReply;
网友评论