I'm trying to convert rest-facebook response to a Post class object as follows:
Post post = gson.fromJson(restFBResponse.toString(), Post.class);
where, restFBResponse
is a post from Facebook. But it is resulting into error:
Exception in thread "main" java.lang.IllegalArgumentException: class com.restfb.types.Post declares multiple JSON fields named type
I think this is due to:
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
}
So, private String type;
is being declared twice, in class Post
and class FacebookType
.
1) If such re-declaration occurs in subclass,should it not be overridden? and
2) How can I overcome this error class com.restfb.types.Post declares multiple JSON fields named type
?
I just written my own class without extension, found no other better option..
public class MyPost{
@Facebook
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
I guess GSON suggested that
@SerializedName("type1")
private String type;
This may resolve issue. But I think there should be a cleaner solution to this..I found that the issue has been marked invalid and no further response was received.
You can write your own serializer and deserializer for gson to serialize and deserialize Post
object.
While doing so use restfb's DefaultJsonMapper
to map Post ob.
Something Like,
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));
}
}
You don't want to declare the same variable "type" in your class Post. As it extends from FacebookType, it implicitly has the variable "type".
Solution:
Simply remove the sentence "private String type;" from your Post class
Replace the "private" word with "protected" in your "type" variable from your FacebookType