gpt4 book ai didi

java - JsonMappingException : No suitable constructor found

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:57:33 28 4
gpt4 key购买 nike

我正在实现他们文档中给出的 firebase 示例。我面临这个错误:

com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.XYZ.$BlogPost]: can not instantiate from JSON object (need to add/enable type information?)

这是我的代码:

    public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
Firebase.setAndroidContext(this);
}

@Override
protected void onStart() {
super.onStart();
// Get a reference to our posts
Firebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");
// Attach an listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println("There are " + snapshot.getChildrenCount() + " blog posts");
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
BlogPost post = postSnapshot.getValue(BlogPost.class);
System.out.println(post.getAuthor() + " - " + post.getTitle());
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
public class BlogPost {
private String author;
private String title;
public BlogPost() {
// empty default constructor, necessary for Firebase to be able to deserialize blog posts
}
public String getAuthor() {
return author;
}
public String getTitle() {
return title;
}
}
}

我已经回答了很多关于同一件事的问题,说要包含反序列化 JSON 所必需的空构造函数。我已经包括在内,但我仍然无法解决问题。这是我要反序列化的 JSON:

{  
"-JRHTHaIs-jNPLXOQivY":{
"author":"gracehop",
"title":"Announcing COBOL, a New Programming Language"
},
"-JRHTHaKuITFIhnj02kE":{
"author":"alanisawesome",
"title":"The Turing Machine"
}
}

我不知道我的代码中缺少什么。感谢任何对此进行重新分级的帮助。

最佳答案

我猜您的 BlogPost 类是您 Activity 的内部类。在这种情况下,Java 会为每个引用包含对象的对象添加一个隐藏字段。而这个隐式字段当然不会出现在您的 JSON 数据中。

要解决这个问题,您应该将 BlogPost 类保存在单独的文件中(这样它就不是内部类)或将其标记为静态类(这会删除隐式字段):

public static class BlogPost {

关于java - JsonMappingException : No suitable constructor found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34338402/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com