以下是我的pojo课程,
public class LocalTrack {
private long id;
private String title;
private String artist;
private String album;
private String path;
private long duration;
private String index;
//constructor
//getter setters for above fields
}
我使用以下代码检索先前保存的json响应。
Map<String, ?> all = tinydb.getAll();
Iterator it = all.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
LocalTrack localTrack = gson.fromJson(pairs.getValue().toString(), LocalTrack.class);
}
pairs.getValue()有以下json。
{"album":"http://MyMp3Song.Com","artist":"04 - Thai Mannai Vanakka","index":"#","path":"/storage/sdcard1/Download/04 - Thai Mannai Vanakkam(MyMp3Song.Com).mp3","title":"04 - Thai Mannai Vanakkam(MyMp3Song.Com)","duration":369424,"id":32004}
当我说gson.fromJson(pairs.getValue().toString(), LocalTrack.class)
时,它会返回以下错误,
java.lang.NullPointerException:尝试调用虚方法 'java.lang.Object com.google.gson.Gson.fromJson(java.lang.String, java.lang.Class)'对空对象引用 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
为什么会这样?
答案 0 :(得分:1)
&#39; gson&#39;对象需要初始化。这是一个链接.. mkyong on how to use gson
Gson gson = new Gson();
Map<String, ?> all = tinydb.getAll();
Iterator it = all.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
LocalTrack localTrack = gson.fromJson(pairs.getValue().toString(), LocalTrack.class);
}