使用GSON Android解析json的空指针异常

时间:2012-11-16 18:37:19

标签: android eclipse json android-asynctask gson

我正在调用一个Web服务,它从数据库中获取数据并输出以下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":"lg@nxtldn.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":"ashshort@short.com","eventPhone":"0778514562","eventKeywords":"cupcakes, store, london, hipster"}]
我附加的

(我已使用http://jsonlint.com/测试了JSON是否有效):

{"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":"lg@nxtldn.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":"ashshort@short.com","eventPhone":"0778514562","eventKeywords":"cupcakes, store, london, hipster"}]}

我正在使用AsyncTask

调用它
public class EventSync extends AsyncTask<String, Integer, EventsList> {

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> events;

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

public void setEventsList(List<Event> 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

目前我只是在尝试测试它以确定它是否会在我使用自定义适配器填充列表视图之前返回。但遗憾的是我收到了以下错误:

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)

我刚接触到android所以我不确定是否有更好的方法来做到这一点或者正确的方法是什么。

是不是我的JSON结构为什么GSON不接受并返回空指针?

非常感谢任何可以提供帮助的人:)

3 个答案:

答案 0 :(得分:1)

尝试更改

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

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

这假设你在webservice中使用了一个类型为Event的数组(在你的例子中显示)来创建这个json。我认为当前的问题是你的json字符串与EventList类不匹配,因此返回null。确保服务和android项目中的Event类匹配。

答案 1 :(得分:0)

在EventsList中,您期望事件的列表(集合),但您追加的JSON实际上是一个对象:“{\”Events \“:”+ output +“}”;也许你希望它看起来像这样:

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

这会将您的单个事件放入一系列潜在事件中。您的用例令人困惑,我不确定您为什么要将单个JSON对象放入数组中,但可能还有更多我缺少的详细信息。

答案 2 :(得分:0)

我发现这是因为我在我的字符串构建器中添加了“/ n”,创建了新行并切断了json的最后一行。谢谢大家