我是个上网的人。我试着调用api并从中获取数据。
使用Java实现序列化JSON对象。但我犯了个错误。
Expected BEGIN_ARRAY but was BEGIN_OBJECT
在.net中,这真的很容易做到。但在爪哇,我不知道该怎么做。
这是我的模特班
public class Dictionary {
@SerializedName("metadata")
@Expose
private Metadata metadata;
@SerializedName("results")
@Expose
private List results = null;
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public List getResults() {
return results;
}
public void setResults(List results) {
this.results = results;
}
}
这里是我的api调用
public class Oxford {
public String URL_OXFORD = "https://od-api.oxforddictionaries.com/api/v1/inflections/en/swimming";
public static List httpGet(String url, String function) {
List dataFromService = new ArrayList();
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpGet request = new HttpGet(url+function);
request.addHeader("content-type", "application/json");
request.addHeader("app_id", "566566");
request.addHeader("app_key", "somekey");
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Dictionary[] response = gson.fromJson(json, Dictionary[].class);
System.out.println(response.length);
for(Dictionary file : response)
{
dataFromService.add(file);
System.out.println(file.toString());
}
} catch (IOException ex) {
}
return dataFromService;
}