Title: null pointer exception parsing json using GSON Android
Tags: android;eclipse;json;android-asynctask;gson
Question: I'm calling a web service which gets the data from the database and outputs the following JSON :

```{"eventId":"1","eventTitle":"opening ceremony","eventCategory":"store","eventSubCategory":"clothing","eventDescription":"This is an event description of some kid for the first event","eventDate":"13/05/2012","eventTime":"14:52","eventAddress":"49 somerset road","eventCity":"southsea","eventCountry":"UK","eventWebsite":"www.nxtldn.com","eventEmail":"anthonymendoza@example.com","eventPhone":"07757491567","eventKeywords":"clothes, street, wear, heart, love"},{"eventId":"2","eventTitle":"cupcakes","eventCategory":"Store","eventSubCategory":"food","eventDescription":"This is an event description of some kid for the second event","eventDate":"17/05/2012","eventTime":"11:22","eventAddress":"12 cleveleys road","eventCity":"london","eventCountry":"UK","eventWebsite":"www.ashshort.com","eventEmail":"anthonymendoza@example.com","eventPhone":"0778514562","eventKeywords":"cupcakes, store, london, hipster"}]
```

which I append (I have tested to see if the JSON is valid using http://jsonlint.com/):

```{"Events":[{"eventId":"1","eventTitle":"opening ceremony","eventCategory":"store","eventSubCategory":"clothing","eventDescription":"This is an event description of some kid for the first event","eventDate":"13/05/2012","eventTime":"14:52","eventAddress":"49 somerset road","eventCity":"southsea","eventCountry":"UK","eventWebsite":"www.nxtldn.com","eventEmail":"anthonymendoza@example.com","eventPhone":"07757491567","eventKeywords":"clothes, street, wear, heart, love"},{"eventId":"2","eventTitle":"cupcakes","eventCategory":"Store","eventSubCategory":"food","eventDescription":"This is an event description of some kid for the second event","eventDate":"17/05/2012","eventTime":"11:22","eventAddress":"12 cleveleys road","eventCity":"london","eventCountry":"UK","eventWebsite":"www.ashshort.com","eventEmail":"anthonymendoza@example.com","eventPhone":"0778514562","eventKeywords":"cupcakes, store, london, hipster"}]}
```

I'm calling it using an AsyncTask

```public class EventSync extends AsyncTask<String, Integer, EventsList&gt; {

EventsList elist1 = new EventsList();

@Override
protected EventsList doInBackground(String... urls) {
    String tempurl = urls[0];
    String output = "";
    InputStream is = null;
    StringBuilder sb = new StringBuilder();
    EventsList list = new EventsList();
    try
    {
        URL url = new URL(tempurl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.connect();
        is = con.getInputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line = null;

        while((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            is.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    output = sb.toString();
    String json = "{\"Events\":" + output + "}";
    System.out.println(json);
    Gson gson = new Gson();
// When debugging this is the line I believe it fails on, It points to a bit of memory but the list is empty.
    EventsList jsonlist = gson.fromJson(json, EventsList.class);

    return jsonlist;
}

@Override 
protected void onPostExecute(EventsList list)
{

    System.out.println("in on post");
    for (Event event : list.getEvents())
    {
        System.out.println(event.getEventId());
    }
}}
```

 

```public class EventsList {

public EventsList(){

}

private List<Event&gt; events;

public List<Event&gt; getEvents()
{
    return events;
}

public void setEventsList(List<Event&gt; events)
{
    this.events = events;
}}
```



```public class Event {

private String eventId;
private String eventTitle;
private String eventCategory;
private String eventSubCategory;
private String eventDescription;
private String eventDate;
private String eventTime;
private String eventAddress;
private String eventCity;
private String eventCountry;
private String eventWebsite;
private String eventEmail;
private String eventPhone;
private String eventKeywords;

public Event()
{

}

// ALL GETS AND SETS
```

At the moment I'm just trying to test it to see if it will return before I use a custom adapter to populate a listview. But unfortunate I am getting the following error:

```11-10 23:37:08.315: E/AndroidRuntime(5592): FATAL EXCEPTION: main
11-10 23:37:08.315: E/AndroidRuntime(5592): java.lang.NullPointerException
11-10 23:37:08.315: E/AndroidRuntime(5592):     at com.nxtldn.trill.EventSync.onPostExecute(EventSync.java:71)
11-10 23:37:08.315: E/AndroidRuntime(5592):     at com.nxtldn.trill.EventSync.onPostExecute(EventSync.java:1)
11-10 23:37:08.315: E/AndroidRuntime(5592):     at android.os.AsyncTask.finish(AsyncTask.java:631)
11-10 23:37:08.315: E/AndroidRuntime(5592):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-10 23:37:08.315: E/AndroidRuntime(5592):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
11-10 23:37:08.315: E/AndroidRuntime(5592):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-10 23:37:08.315: E/AndroidRuntime(5592):     at android.os.Looper.loop(Looper.java:137)
11-10 23:37:08.315: E/AndroidRuntime(5592):     at android.app.ActivityThread.main(ActivityThread.java:4745)
11-10 23:37:08.315: E/AndroidRuntime(5592):     at java.lang.reflect.Method.invokeNative(Native Method)
11-10 23:37:08.315: E/AndroidRuntime(5592):     at java.lang.reflect.Method.invoke(Method.java:511)
11-10 23:37:08.315: E/AndroidRuntime(5592):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-10 23:37:08.315: E/AndroidRuntime(5592):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-10 23:37:08.315: E/AndroidRuntime(5592):     at dalvik.system.NativeStart.main(Native Method)
```

I new to android so I'm not sure if there is a better way of doing this or what the correct way is. 

Is it down the the structure of my JSON why the GSON wont accept and returns null pointers? 

Many thanks in advance to anyone that can help :)


Here is the accepted answer: I found it was due to me adding "/n" to my string builder, creating the new line and chopping off the final } of the json. Thanks everyone


Here is another answer: In EventsList you are expecting a List(Collection) of events but the JSON you append is actually an Object: "{\"Events\":" + output + "}"; Perhaps you wanted it to look like this:

```"{\"Events\":[" + output + "]}";
```

This puts your single event into an array of potential events. Your use case is confusing, I'm not sure why you want to put a single JSON object into an array but perhaps there are more details I'm missing.

Comment for this answer: Sorry, the first JSON output is missing a square bracket which was removed when copying to SOF. If you could please place your attention to the second JSON, it is a JSON Object of Events which holds a JSON Array of JSON Objects. Am i correct in say that? Which I am then trying to convert using GSON into my two seperate Classes.
Comment for this answer: Try calling it "events" instead of "Events"

Here is another answer: Try changing 

```EventsList jsonlist = gson.fromJson(json, EventsList.class);
```

to

```Event[] jsonlist = gson.fromJson(json, Event[].class); 
```

This is assuming that you have used an array of type Event (shown above in your example) in your webservice to create this json. I think the current problem is that your json string does not match up to the class EventList therefore returning null. Ensure that the Event class in your service and android project match.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 3, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2012:00:11/16/12', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<android><eclipse><json><android-asynctask><gson>', 'Title': 'null pointer exception parsing json using GSON Android', 'ViewCount': 825, 'id': 13422448, 'user_AboutMe': '<p>Trying to learn android, failing miserably.</p>\n', 'user_AccountId': 2051219.0, 'user_DisplayName': 'tke19', 'user_Reputation': 11.0, 'user_Views': 20.0, 'user_id': 1830194.0}}