java 获取代码行数据_使用Java尝试从API获取数据

本文讲述了作者在尝试使用Java从API获取数据时遇到的问题,具体为在反序列化JSON对象时遇到了`Expected BEGIN_ARRAY but was BEGIN_OBJECT`的错误。作者对比了.NET中的简单操作,并分享了其定义的数据模型(Dictionary类)和API调用方法(Oxford类),但没有给出具体的解决方案。
摘要由CSDN通过智能技术生成

我是个上网的人。我试着调用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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值