[英]JSON data is not fetching using Retrofit
I am using retrofit networking library for fetching data from server.I am using MVVM architecture model to create an app.When app starts it is showing some exception and not fetching data. 我正在使用改造网络库从服务器中获取数据,我正在使用MVVM体系结构模型来创建应用程序,当应用程序启动时,它会显示一些异常而不是获取数据。
java.lang.IllegalStateException:Expected BEGIN_OBJECT but was BEGIN_ARRAY at Line 1 Column 2 path $.
java.lang.IllegalStateException:预期为BEGIN_OBJECT,但在行1列2路径$处为BEGIN_ARRAY。
I am fail to understand what it is trying to say.Below is my code. 我不明白它要说的是什么。下面是我的代码。
RetrofitClient.java RetrofitClient.java
public class RetrofitClient {
private static Retrofit retrofit = null;
private static final String URL = "https://example.com/";
public static Retrofit getInstance(){
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20,TimeUnit.SECONDS)
.writeTimeout(20,TimeUnit.SECONDS)
.build();
if(retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build();
}
return retrofit;
}
private RetrofitClient(){
}
}
ApiService.class ApiService.class
public interface ApiService {
@GET("getUsers")
Call<User> getUser();
}
User.java User.java
public class User {
@SerializedName("name")
@Expose
private String name;
@SerializedName("age")
@Expose
private String age;
public User(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
UserRepository.java UserRepository.java
public class UserRepository {
Context context;
public UserRepository(Context context) {
this.context = context;
}
public void getUserList(){
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
Call<User> userList = apiService.getUser();
userList.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
Log.d("Response", String.valueOf(response.body()));
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(context,t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
MainActivity.java MainActivity.java
public class MainActivity extends AppCompatActivity {
UserRepository userRepository;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,AddUser.class);
startActivity(i);
}
});
userRepository = new UserRepository(this);
userRepository.getUserList();
}
API Response API响应
[
{
"name": "Link",
"age": "5"
},
{
"name": "Rhea",
"age": "24"
},
{
"name": "Don",
"age": "10"
},
{
"name": "oman",
"age": "30"
},
{
"name": "Ron",
"age": "18"
},
{
"name": "roman",
"age": "25"
}
]
Someone please let me know why above exception is showing am I doing something wrong. 有人请让我知道为什么以上例外说明我做错了什么。 Any help would be appreciated.
任何帮助,将不胜感激。
THANKS 谢谢
Your JSON data is an array of user objects, but you are trying to parse a single User Object. 您的JSON数据是一个用户对象数组,但是您正在尝试解析单个用户对象。 Use List to indicate that you want to parse an array of User objects, something like below in your UserRepository class:
使用列表表示您要解析User对象的数组,类似于UserRepository类中的以下内容:
public void getUserList() {
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
Call<List<User>> userList = apiService.getUser();
userList.enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
Log.d("Response", String.valueOf(response.body()));
}
@Override
public void onFailure(Call<List<User>> call, Throwable t) {
Toast.makeText(context,t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
Also your ApiService interface should reflect that. 同样,您的ApiService接口应反映出这一点。
public interface ApiService {
@GET("getUsers")
Call<List<User>> getUser();
} }
in your ApiService Interface you wrote this 在您的ApiService接口中,您编写了此代码
@GET("getUsers")
Call<User> getUser();
but based on your json responce really you need a list of Users , not a single user 但是根据您的json响应,您实际上需要一个Users列表,而不是一个用户
@GET("getUsers")
Call<List<User>> getUser();
also in UserRepository class you should have something like this. 同样在UserRepository类中,您应该具有类似的内容。
public class UserRepository {
Context context;
public UserRepository(Context context) {
this.context = context;
}
public void getUserList(){
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
Call<List<User>> userList = apiService.getUser();
userList.enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
Log.d("Response", String.valueOf(response.body()));
}
@Override
public void onFailure(Call<List<User>> call, Throwable t) {
Toast.makeText(context,t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
Isn't expected BEGIN_OBJECT but was BEGIN_ARRAY
explict? 是不是
expected BEGIN_OBJECT but was BEGIN_ARRAY
显式的?
It is because that array has no name and it starts with [
instead of {
... 这是因为该数组没有名称,并且以
[
而不是{
...
valid JSON (as expected by GSON) would look alike this: 有效的JSON(如GSON所期望的)看起来像这样:
{
"users": [
{"name": "Link","age": "5"},
{"name": "Rhea","age": "24"},
{"name": "Don","age": "10"},
{"name": "oman", "age": "30"},
{"name": "Ron", "age": "18"},
{"name": "roman", "age": "25"}
]
}
If you cannot change the API, then intercept the call and fix the input JSON, before mapping it. 如果无法更改API,则在映射它之前,请拦截该调用并修复输入的JSON。
The return type is also wrongful, because that should be ArrayList<User>
. 返回类型也是错误的,因为那应该是
ArrayList<User>
。
PS: that top-level array users
would need it's own data model. PS:顶级数组
users
将需要它自己的数据模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.