You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java调用Yelp API触发IllegalStateException问题求助

解决Java调用Yelp API的IllegalStateException问题

这个异常的核心原因很明确:你用的JSON解析库(比如Gson)期望解析成数组(BEGIN_ARRAY),但Yelp API实际返回的JSON根节点是对象(BEGIN_OBJECT),两者结构不匹配导致解析失败触发onFailure。

排查与修复步骤

  1. 核对API返回的JSON结构
    先确认Yelp API返回的实际JSON格式,它的根结构通常是这样的(示例):

    {
      "businesses": [
        {
          "id": "abc123",
          "name": "示例餐厅",
          "rating": 4.5
        }
      ],
      "total": 20,
      "region": {...}
    }
    

    这里根节点是一个对象,里面包含businesses数组字段,而不是直接返回数组。

  2. 调整DataResponse类结构
    如果你的DataResponse类直接定义成数组/List类型,或者没有对应JSON的根对象结构,就会报错。你需要让DataResponse类完全匹配JSON的根对象:

    import com.google.gson.annotations.SerializedName;
    import java.util.List;
    
    public class DataResponse {
        @SerializedName("businesses") // 对应JSON里的businesses字段
        private List<Business> businesses;
        
        @SerializedName("total")
        private int total;
        
        // 其他需要的字段,比如region等
        
        // Getter和Setter方法
        public List<Business> getBusinesses() {
            return businesses;
        }
    
        public void setBusinesses(List<Business> businesses) {
            this.businesses = businesses;
        }
    
        public int getTotal() {
            return total;
        }
    
        public void setTotal(int total) {
            this.total = total;
        }
    }
    
    // 对应的Business子类
    class Business {
        @SerializedName("id")
        private String id;
        
        @SerializedName("name")
        private String name;
        
        @SerializedName("rating")
        private double rating;
        
        // Getter和Setter
    }
    
  3. 修正网络请求的解析目标
    比如用Retrofit的话,你的API接口应该定义为返回Call<DataResponse>,而不是Call<List<Business>>:

    public interface YelpApi {
        @GET("businesses/search")
        Call<DataResponse> searchBusinesses(
            @Header("Authorization") String authHeader,
            @Query("term") String term,
            @Query("location") String location
        );
    }
    

额外检查点

  • 确认@SerializedName的字段名和JSON里的完全一致(注意大小写,Yelp API用蛇形命名,比如businesses,不要写成Businesses)。
  • 用Postman直接调用Yelp API,复制返回的JSON,和你的DataResponse类字段逐一比对,确保没有遗漏或错误匹配。

内容的提问来源于stack exchange,提问作者Raymond Truong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 23:59:54