网络请求(四)Retrofit实战——金山词霸查词API&遇到的问题

本文介绍了使用Retrofit进行金山词霸API查词的实战过程,包括遇到的JSON解析问题。当单词无第三人称复数形式时,API返回的`word_third`字段有时为数组,有时为字符串,导致解析错误。通过断点调试发现问题所在,并决定采用JSONObject解析以解决问题。
摘要由CSDN通过智能技术生成

准备工作

在上一篇博客 网络请求(三)——Retrofit的get和post请求的用法 中,每日一词的json格式比较简单,于是试了一下使用API的查词接口

我使用的API
http://dict-co.iciba.com/api/dictionary.php?w=good&type=json&key=0CD3A4C079D2D23C683BBFF96300E924

JSON结构

在这里插入图片描述

代码

一开始,事情进行的很顺利……

  • 新建用于接收服务器返回数据的类,新建接口
public interface GetRequest_Interface {
   
    //用get方式发送网络请求
    @GET("api/dictionary.php?w=go&type=json&key=0CD3A4C079D2D23C683BBFF96300E924")
    //接收网络请求数据的方法
    Call<Translation> getCall();

    @POST("api/dictionary.php?")
    Call<Translation> postCall(
            @Query("w") String word, @Query("type") String type, @Query("key") String key);
}
  • 创建Retrofit实例
  • System.out.println(translation.getSymbols().get(0).getParts().get(0).getMeans().get(0));
  • 这句中,先得到"Symbols",再get(0)获得数组第一个参数([ ]里的),得到"Parts",get(0)获取第一个参数,得到"Means",再获得第一个中文意思
private void request() {
   
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://dict-co.iciba.com/")
            .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析
            .build();

    GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
        Call<Translation> call = request.getCall();
        call.enqueue(new Callback<Translation>() {
   
            @Override
            public void onResponse(Call<Translation> call, Response<Translation> response) {
   
                if(response.isSuccessful()) {
   
                    Translation translation = response.body();
                        System.out.println(translation.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值