Solr的-Java错误:类com.restfb.types.Post声明了一个名为类型的多个领域J

2019-10-17 23:02发布

我想休息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 Postclass FacebookType

1)如果在子类中发生这样的重新声明,它应该不能被重写? 和

2)我怎样才能克服这种错误class com.restfb.types.Post declares multiple JSON fields named type

Answer 1:

我只写我自己的类不带扩展名,未发现有其他更好的选择..

public class MyPost{

    @Facebook
    private String type;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}


Answer 2:

我想GSON建议

@SerializedName( “TYPE1”)私人字符串类型;

这可能会解决问题。 但是,我觉得应该有一个更清洁的解决this..I发现该问题已标记为无效,并没有收到任何进一步的回应。



Answer 3:

您可以编写自己的串行器和解串为GSON序列化和反序列化Post的对象。

这样做虽然使用restfb的DefaultJsonMapper映射后OB。

就像是,

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));
        }
    }


Answer 4:

你不想在声明类帖子相同的变量“类型”。 如从FacebookType延伸,它隐含具有变量“类型”。

解:

Simply remove the sentence "private String type;" from your Post class
Replace the "private" word with "protected" in your "type" variable from your FacebookType


文章来源: Solr-java error: class com.restfb.types.Post declares multiple JSON fields named type