Gson解码PHP编码的Json

时间:2013-07-20 23:55:55

标签: java json gson

我正在使用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或两者的值?

1 个答案:

答案 0 :(得分: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服务获得的内容);