J.Doe J.Doe - 2 months ago 20
JSON Question

de-serializing an object through gson results in null pointer exception

Following is my pojo class,

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
}


Im using the following code to retrieve the json response that is saved previously.

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() has got the following 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}


When I say,
gson.fromJson(pairs.getValue().toString(), LocalTrack.class)
it returns the following error,


java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.Object com.google.gson.Gson.fromJson(java.lang.String,
java.lang.Class)' on a null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)


why is that so?

Answer

The 'gson' object needs to be initialized. Here is a link.. 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);
            }
Comments