https://www.freshbytelabs.com/2018/05/how-to-fix-expected-beginarray-but-was.html

HOW TO FIX "EXPECTED BEGIN_ARRAY BUT WAS BEGIN_OBJECT" IN RETROFIT ?

MAY 09, 2018 / BY NAVNEET KRISHNA / IN BEGIN_ARRAYBEGIN_OBJECTEXPECTED BEGIN_ARRAY BUT WAS BEGIN_OBJECTGSONJSON ARRAYJSON OBJECTNAVNEETPOJORETROFIT / WITH NO COMMENTS / 

 
Before we begin, keep this in mind

begin_array means the json response is an array which will look something like this [{},{},..]
begin_object means the json response is an object which will look something like this {....}

gson is one cool library that will provide us with cool tips in the form of errors while handling json responses. One such tip is "expected begin_array but was begin_object". These tips/errors are quite self explanatory, we can now look deeper into these errors.

While handling responses using retrofit, we often tend to come across an error "expected begin_array but was begin_object", which is thrown by gsonObviously this means that we are trying to parse the response as if it is a json array response but when actually it is a json object response. But still we come across these errors a lot of time. We will be looking in detail about such situations in this post.

First add the following dependencies in your app's build.gradle file

compile 'com.squareup.retrofit2:retrofit:2.3.0' 
compile 'com.squareup.retrofit2:converter-gson:2.3.0'

PARSING JSON OBJECT RESPONSES :

  • A  json object  response is of the form {....}.  The json object may also contain a json array like the below example where the json object contains a json array named user_array.
{
"username":"jon",
"email":"jon@email.com",
"user_array": [
{
"user_address":"jon",
"user_location":"jon@email.com"
}, {..},
.
.
]
}

In order to parse the above json object you can either use the JsonObject from gson or create pojo classes

1. PARSING USING JSONOBJECT  FROM GSON

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("base_url")
.addConverterFactory(GsonConverterFactory.create())
.build();

RequestInterface request = retrofit.create(RequestInterface.class);
Call<JsonObject> call=request.getJson();
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
progressDialog.dismiss();
String s= String.valueOf(response.get("username"));
JsonArray user_array= response.getAsJsonArray("user_array");
Toast.makeText(PrintTicket.this,response.toString(),Toast.LENGTH_SHORT).show();
}

@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(PrintTicket.this,t.toString(),Toast.LENGTH_SHORT).show();
}
});

RequestInterface.java
public interface RequestInterface { @GET("api_endpoint") Call<JsonObject> getJson(); }

2. PARSING USING POJO  CLASS

You can automatically generate the pojo classes by pasting your json response structure in http://www.jsonschema2pojo.org/ .
 
FYI : after pasting the response structure in http://www.jsonschema2pojo.org/ ,  set the source type to JSON and Annotation style to Gson , now click preview button and you can see generated pojo class/classes
 
For the above case you will need to generate two classes like below
 
Example.java
 
public class Example {

@SerializedName("username")
@Expose
private String username;
@SerializedName("email")
@Expose
private String email;
@SerializedName("user_array")
@Expose
private List<UserArray> userArray = null; public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public List<UserArray> getUserArray() {
return userArray;
} public void setUserArray(List<UserArray> userArray) {
this.userArray = userArray;
} }
 
UserArray.java
 
public class UserArray {

@SerializedName("user_address")
@Expose
private String userAddress;
@SerializedName("user_location")
@Expose
private String userLocation; public String getUserAddress() {
return userAddress;
} public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
} public String getUserLocation() {
return userLocation;
} public void setUserLocation(String userLocation) {
this.userLocation = userLocation;
} }
 
In the above  pojo classes, we have used @SerializedName annotation which will help us to map the class variables to respective keys in the response json. For example, in UserArray.java, the string variable userAddress is correctly mapped to user_address by using the @SerializedName annotation like this

@SerializedName("user_address")
@Expose
private String userAddress;
The Example.java is for parsing the outer json object whereas UserArray.java is for parsing the inner json object which should be parsed as a list(since there is a list of objects in user_array)
 
 
Now the retrofit call should be made like the following

ArrayList<RouteStop> user_array;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("base_url")
.addConverterFactory(GsonConverterFactory.create())
.build(); RequestInterface request = retrofit.create(RequestInterface.class);
Call<Example> call=request.getJson();
call.enqueue(new Callback<Example>() {
@Override
public void onResponse(Call<Example> call, Response<Example> response) {
progressDialog.dismiss();
String user_name= response.getUsername();
user_array= new ArrayList<>(response.getUserArray());
Toast.makeText(PrintTicket.this,response.toString(),Toast.LENGTH_SHORT).show();
} @Override
public void onFailure(Call<Example> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(PrintTicket.this,t.toString(),Toast.LENGTH_SHORT).show();
}
});
RequestInterface.java
public interface RequestInterface {
@GET("api_endpoint")
Call<Example> getJson();
}

The error "expected begin_array but was begin_object" occurs  if you are trying to parse the above response using Call<List<Example>> call=request.getJson(); because by using <List<Example>> we are clearly making an array request but we need to make an object request since response is of the form {..}

 
Similarly we get the error "expected begin_object but was begin_array"  when we are trying to make an object request were the response is of the form [{},{},..]. In such case we should make the call like Call<List<Example>>
 
 
 

RELATED POSTS:

HOW TO FIX "EXPECTED BEGIN_ARRAY BUT WAS BEGIN_OBJECT" IN RETROFIT ?的更多相关文章

  1. Expected BEGIN_ARRAY but was BEGIN_OBJECT

    Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3519 path $.data[1].inspector_user Gson 中 ...

  2. 利用Retrofit, RxJava获取网络内容

    Retrofit & RxJava 关于如何使用Retrofit和RxJava请阅读参考中的两篇文章. Retrofit处理数据 Retrofit是在什么时候处理从网络中获取到的json数据的 ...

  3. realm怎样支持hashmap

    realm不支持hashmap这种形式stackoverflow给出了解决方案http://stackoverflow.com/ques... class MyData extends RealmOb ...

  4. Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path 解决办法

    返回数据解析错误 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT ...

  5. gson Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path

    返回数据解析错误 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT ...

  6. Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2

    原因是解析的时候多了,逗号,或是 \ 解决方法:一 revJson=revJson.replace("\\", "");//去掉'/' revJson=revJ ...

  7. ERROR 3009 (HY000): Column count of mysql.user is wrong. Expected 45, found 42. Created with MySQL 50560, now running 50725. Please use mysql_upgrade to fix this error.

    centos7.5 登入mysql,进行授权报错 问题: mysql> grant all privileges on *.* to 'lvhanzhi'@'%' identified by ' ...

  8. Column count of mysql.user is wrong. Expected 43, found 42. Created with MySQL 50518, now running 50641. Please use mysql_upgrade to fix this error.

    出现问题: Column count of mysql.user is wrong. Expected 43, found 42. Created with MySQL 50518, now runn ...

  9. [React] Fix "React Error: Rendered fewer hooks than expected"

    In this lesson we'll see an interesting situation where we're actually calling a function component ...

随机推荐

  1. Java常量池解析与字符串intern简介

    在Java应用程序运行时,Java虚拟机会保存一份内部的运行时常量池,它区别于class文件的常量池,是class文件常量池映射到虚拟机中的数据结构. 关于class文件常量池的部分可以参考之前的博文 ...

  2. vim 创建文件自动生成头部注释

    知识点: 1. autocmd命令: 当读写一个文件时,自动执行指定的命令; 2. autocmd event: BufNewFile 当文件不存在时开始写文件; 3. exec命令 execute命 ...

  3. python中unicode和unicodeescape

    在python中,unicode是内存编码集,一般我们将数据存储到文件时,需要将数据先编码为其他编码集,比如utf-8.gbk等. 读取数据的时候再通过同样的编码集进行解码即可. #python3 & ...

  4. 浅析StackTrace

    我们在学习函数调用时,都知道每个函数都拥有自己的栈空间.一个函数被调用时,就创建一个新的栈空间.那么通过函数的嵌套调用最后就形成了一个函数调用堆栈.在c#中,使用StackTrace记录这个堆栈.你可 ...

  5. gcc 编译流程分析

    //test.c #include<stdio.h> int main() { ,y=; printf("x=%d y=%d\n",x,y); ; } 1:预处理阶段, ...

  6. 确定文件的位置--浏览文件夹对话框folderBrowserDialog

    private void button1_Click(object sender, EventArgs e) { folderBrowserDialog1.ShowNewFolderButton = ...

  7. 关于ajax跨域的一些说说

    跨域:跨当然是跨过去,域当然是别的服务器 (说白点就是去别服务器上取东西) 只要协议.域名.端口有任何一个不同,都被当作是不同的域 ajax 是一种请求响应无刷新技术(xmlhttqrequest对象 ...

  8. 【BZOJ】1053: [HAOI2007]反素数ant(贪心+dfs)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1053 约数个数等于分解出的质因数的(指数+1)的乘积这个就不用说了吧... 然后好神的题在于贪心.. ...

  9. ie中自动识别单屏与双屏(js)

    <!DOCTYPE html> <html> <head> <meta name="viewport" content="wid ...

  10. 【theano】tutorial

    http://deeplearning.net/software/theano/tutorial/index.html#tutorial