我正在实现他们的文档中给出的firebase示例.我正面临这个错误:
com.fasterxml.jackson.databind.JsonMappingException:[简单类型,类com.XYZ $博文]发现型没有合适的构造函数:不能从JSON对象实例化(需要添加/启用类型的信息?)
这是我的代码:
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
班级是你活动的内在阶级.在这种情况下,Java会为引用包含对象的每个对象添加一个隐藏字段.而这个隐含字段当然不会出现在您的JSON数据中.
要解决这个问题,您应该将BlogPost
类保留在单独的文件中(以便它不是内部类)或将其标记为静态类(删除隐式字段):
public static class BlogPost {