0

我正在使用 PHP 生成Json从数据库查询中获取的内容。结果如下所示:

[
    {
        "title":"Title 1",
        "description":"This is description 1",
        "add_date":"2013-07-17 10:07:53"
    },{
        "title":"Title 2",
        "description":"This is description 2",
        "add_date":"2013-07-17 10:07:53"
    }
]

我正在使用 Gson 来解析数据,如下所示:

public class Search{

    public Search(String text){
        try{

            // Snipped (gets the data from the website)

            Gson json = new Gson();
            Map<String, Event> events = json.fromJson(resultstring, new TypeToken<Map<String, Event>>(){}.getType());

            System.out.print(events.get("description"));

        }catch(IOException ex){
            Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

class Event {
    private String description;
}

这是我在尝试运行代码时收到的消息:

线程“AWT-EventQueue-0”com.google.gson.JsonSyntaxException 中的异常:java.lang.IllegalStateException:预期 BEGIN_ARRAY 但在第 1 行第 3 列是 BEGIN_OBJECT

我将如何遍历每一个来获得 的值descriptiontitle或两者兼而有之?

4

1 回答 1

2

对您正在做的事情进行了一些更正,您应该一切顺利:

class Event {
    private String description;
    private String title;
    @SerializedName("add_date") private String addDate;

   public getDescription() {
       return description;
   }
}


 public Search(String text){
    try{

        // Snipped (gets the data from the website)

        Gson json = new Gson();
        Event[] events = json.fromJson(resultstring, Event[].class);

        System.out.print(events[0].getDescription());

    }catch(IOException ex){
        Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex);
    }

}

我已经更正了您的 bean 类并更改了您转换为的类型(数组Event,因为这是您实际从 PHP 服务获得的);

于 2013-07-21T00:09:20.333 回答