我正在尝试将rest-facebook响应转换为Post类对象,如下所示:
Post post = gson.fromJson(restFBResponse.toString(), Post.class);
式中,restFBResponse
为来自Facebook的帖子。但是它会导致错误:
Exception in thread "main" java.lang.IllegalArgumentException: class com.restfb.types.Post declares multiple JSON fields named type
我认为这是由于:
1)
class Post extends NamedFacebookType{
@Facebook
private String type;
//and some more class members
}
2)
class NamedFacebookType extends FacebookType {
//few class members
}
3)
class FacebookType implements Serializable {
@Facebook
private String type;
//and some more class members
}
因此,private String type;
在class Post
和class FacebookType
中被声明了两次。
1)如果这种重新声明发生在子类中,它不应该被重写吗?和
2)我如何克服这个错误class com.restfb.types.Post declares multiple JSON fields named type
我刚刚编写了自己的类,没有扩展,没有其他更好的选择。
public class MyPost{
@Facebook
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
我猜GSON建议
@SerializedName(类型1)private String类型;
这可能解决问题。但我认为应该有一个更清晰的解决方案,我发现这个问题已被标记为无效,没有收到进一步的回应。
您可以为gson编写自己的序列化器和反序列化器来序列化和反序列化Post
对象。
使用restfb的DefaultJsonMapper
来映射Post对象
,
private Gson gson = new GsonBuilder()
.serializeNulls()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(Post.class, new PostDeserializer())
.registerTypeAdapter(Post.class, new PostSerializer())
.setPrettyPrinting()
.create();
private DefaultJsonMapper dMapper = new DefaultJsonMapper();
private class PostDeserializer implements JsonDeserializer<Post> {
@Override
public Post deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext context) throws JsonParseException {
Post post = dMapper.toJavaObject(jsonElement.toString(), Post.class);
return post;
}
}
private class PostSerializer implements JsonSerializer<Post> {
@Override
public JsonElement serialize(Post post, Type type,
JsonSerializationContext context) {
return gson.toJsonTree(dMapper.toJson(post));
}
}
您不希望在类Post中声明相同的变量"type"。当它从FacebookType扩展时,它隐式地具有变量"type"。
解决方案:
Simply remove the sentence "private String type;" from your Post class
Replace the "private" word with "protected" in your "type" variable from your FacebookType