gpt4 book ai didi

java - Gson解码json

转载 作者:行者123 更新时间:2023-12-02 06:53:06 25 4
gpt4 key购买 nike

我正在使用 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;
}

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

Exception in thread "AWT-EventQueue-0" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3

如何循环遍历每个值以获取 descriptiontitle 或两者的值?

最佳答案

对您正在做的事情进行一些更正,您应该可以开始了:

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 服务获取的内容);

关于java - Gson解码json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17767808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com