我有来自服务器的 json 响应。还有加工。
问题是我无法data
使用来自使用gson
.
public class Main{
public static void main(String[] args) {
try {
String url = "https://ghibliapi.herokuapp.com/films";
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
// response.append("\n");
}
in.close();
// System.out.println(response.toString().replaceAll("^.|.$", ""));
String resString = response.toString().replaceAll("^.|.$", "");
Gson gson = new Gson();
String gsonString = gson.toJson(resString);
System.out.println(gsonString);
Data data = gson.fromJson(resString, Data.class);
System.out.println(data);
//
// String name = (String) jsonObject.get("title");
// System.out.println(name);
// Ghibli ghibli = new Ghibli();
// ghibli.startApp();
} catch (IOException ex) {
Logger.getLogger(Ghibli.class.getName()).log(Level.SEVERE, null, ex);
}
// ghibli.getData("https://ghibliapi.herokuapp.com/films");
}
}
我的数据类看起来很简单,字段和构造函数:
class Data {
private String id;
private String title;
@SerializedName("original_title")
private String mOriginal_title;
@SerializedName("original_title_romanised")
private String mOriginal_title_romanised;
private String description;
private String director;
private String producer;
@SerializedName("release_date")
private int mRelease_date;
@SerializedName("running_time")
private int mRunning_time;
@SerializedName("rt_score")
private int mRt_score;
private String[] people;
private String[] species;
private String[] locations;
private String[] vehicles;
private String[] url;
public Data(String id, String title, String mOriginal_title, String mOriginal_title_romanised, String description, String director, String producer, int mRelease_date, int mRunning_time, int mRt_score, String[] people, String[] species, String[] locations, String[] vehicles, String[] url) {
this.id = id;
this.title = title;
this.mOriginal_title = mOriginal_title;
this.mOriginal_title_romanised = mOriginal_title_romanised;
this.description = description;
this.director = director;
this.producer = producer;
this.mRelease_date = mRelease_date;
this.mRunning_time = mRunning_time;
this.mRt_score = mRt_score;
this.people = people;
this.species = species;
this.locations = locations;
this.vehicles = vehicles;
this.url = url;
}
}
请求的去向(就在链接“https://ghibliapi.herokuapp.com/films”):
问题是我对数据的错误陈述。由于不是一个特定的来自服务器,
data
而是很多,所以我需要修复我的解析器List<Data> datas = gson.fromJson(response.toString(), new TypeToken<ArrayList<Data>>(){}.getType());
.这使您可以创建大量数据,而不仅仅是一个。