HOW TO FIX "EXPECTED BEGIN_ARRAY BUT WAS BEGIN_OBJECT" IN RETROFIT ?
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_ARRAY, BEGIN_OBJECT, EXPECTED BEGIN_ARRAY BUT WAS BEGIN_OBJECT, GSON, JSON ARRAY, JSON OBJECT, NAVNEET, POJO, RETROFIT / WITH NO COMMENTS / ![]()
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 gson. Obviously 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
.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
2. PARSING USING POJO CLASS
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;
}
}
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;
}
}
@SerializedName("user_address")
@Expose
private String userAddress;
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();
}
});
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 {..}
RELATED POSTS:
Certificate Pinning in Retrofit using CertificatePinnerUsage Scenario : We may have often connected our client side apps to a lot of web servers. We may build our apps this way easily, but how can we ens… Read More
How to fix some common errors during admob implementation ?This tutorial is basically a walkthrough of some common admob errors. You might have come across these issues at least once during admob sdk integrat… Read More
Some Admob tips to be notedIn this tutorial, let us have a short walkthrough of a series of tips which i have noted while implementing google admob in my android applications … Read More
Adding Ads to Android App using Google AdmobMaking apps are always hard work. This includes days/months of testing and feature iterations. Implementing ads can be one solution where your work f… Read More
Firebase Crashlytics integration in AndroidIt takes an immense amount of hard work to build an android application and then subsequently maintain it in playstore(or any other similar marketpla… Read More
HOW TO FIX "EXPECTED BEGIN_ARRAY BUT WAS BEGIN_OBJECT" IN RETROFIT ?的更多相关文章
- 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 中 ...
- 利用Retrofit, RxJava获取网络内容
Retrofit & RxJava 关于如何使用Retrofit和RxJava请阅读参考中的两篇文章. Retrofit处理数据 Retrofit是在什么时候处理从网络中获取到的json数据的 ...
- realm怎样支持hashmap
realm不支持hashmap这种形式stackoverflow给出了解决方案http://stackoverflow.com/ques... class MyData extends RealmOb ...
- Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path 解决办法
返回数据解析错误 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT ...
- gson Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path
返回数据解析错误 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT ...
- Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
原因是解析的时候多了,逗号,或是 \ 解决方法:一 revJson=revJson.replace("\\", "");//去掉'/' revJson=revJ ...
- 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 ' ...
- 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 ...
- [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 ...
随机推荐
- hdu1331(记忆化搜索)
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; typed ...
- Unix系统编程()信号类型和默认行为
信号类型和默认行为 就是讲了有多少个信号类型 好多啊,后面用到了再看...
- Android——保存和恢复用户状态
onSaveInstanceState 保存 在暂停之后和保存之前调用 onRestoreInstanceState 恢复 再启动之后和显示之前调用 package com.example.chens ...
- 记一次安装多版本php的四个雷区,你踩着了吗
记一次安装多版本php的四个雷区,你踩着了吗 技术小疯子关注3人评论740人阅读2018-06-29 15:00:30 记一次安装多版本的php的四个雷区,你踩着了吗 需求:公司需要在同一台服 ...
- php之道
PHP The Right Way. Tweet 欢迎 目前网络上充斥着大量的过时资讯,让 PHP 新手误入歧途,并且传播着错误的实践以及不安全的代码.PHP 之道 收集了现有的 PHP 最佳实践.编 ...
- C++ 运算符重载二(一元运算符重载)
//一元运算符重载 #include<iostream> using namespace std; class Point { public: Point(int x,int y){ th ...
- Differential Geometry之第八章常Gauss曲率曲面
第八章.常Gauss曲率曲面 1.常正Gauss曲率曲面 2.常负Gauss曲率曲面与Sine-Gordon方程 3.Hilbert定理 4.Backlund变换 4.1.线汇与焦曲面 4.2.Bac ...
- Lifecycle for overriding binding, validation, etc,易于同其它View框架(Tiles等)无缝集成,采用IOC便于测试。
Lifecycle for overriding binding, validation, etc,易于同其它View框架(Tiles等)无缝集成,采用IOC便于测试. 它是一个典型的教科书式的mvc ...
- RAID的简单说明
RAID,为 Redundant Arrays of Independent Disks 的简称,中文为廉价※冗余磁盘阵列 . 磁盘阵列 其实也分为软阵列 (Software Raid) 和硬阵列 ( ...
- CListBox自动换行显示
需要在ListBox控件中显示一些信息.为方便查看,不使用水平滚动条.当要输出的字符串占用的宽度超过ListBox的宽度时,截断字符串,剩余的在下一行显示. 1. 计算ListBox所占的宽度,用Ge ...