【问题标题】:Gson decode jsonGson解码json
【发布时间】:2020-06-01 23:13:24
【问题描述】:

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

【问题讨论】:

    标签: java json gson


    【解决方案1】:

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

    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 服务获得的);

    【讨论】:

    • 有效,但我收到此错误:cannot find symbol symbol: class SerialzedName location: class Event。另外,你为什么要序列化它?
    • @RyanNaddy 这个注解告诉你不要使用字段名和json属性的直接对应。但是,您需要导入注释。这就是你得到的错误
    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 2012-01-02
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多