我正在构建一个应用程序并有一个User
对象:
public class User {
private Integer id = null;
private String username = null;
private String password = null;
private String first_name = null;
private String last_name = null;
private String email = null;
private String phone = null;
private String avatar = null;
private String role = null;
private Boolean confirmed = null;
private Boolean active = null;
private String created_at = null;
private String updated_at = null;
private String sex = null;
private Object company = null;
}
这个对象(类)包含 setter 和 getter。当授权响应到来时 - 我正在使用下一个回调处理它:
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
ApiResponse apiResponse = response.body();
Log.i("log_i", apiResponse.getData().toString());
JsonReader jsonResponse = new JsonReader(new StringReader(apiResponse.getData().toString()));
jsonResponse.setLenient(true);
try {
User user = new Gson().fromJson(jsonResponse, User.class);
Log.i("log_i", user.toString());
Toast.makeText(context, apiResponse.getMessage(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.i("log_i", e.getMessage());
Toast.makeText(context, "Failed to authorize in case of application exception.", Toast.LENGTH_SHORT).show();
}
}
在 try{} 之后进入 FIRT 行之后 - 它崩溃了,下一个错误是日志中的 apperas:
I/log_i: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 147 path $.avatar
记录的 JSON:
{
id=4,
username=admin,
first_name=Test,
last_name=User,
[email protected],
phone=012.345.678,
confirmed=true,
active=true,
avatar=https://path/to/avatar.png,
role=admin,
created_at=2017-02-24T14: 22: 50+00: 00,
updated_at=null,
company_id=2.0,
sex=m,
company={
id=2.0,
title=companyTitle,
active=true,
created_at=2017-02-24T14: 22: 50+00: 00,
updated_at=null,
deleted_at=2017-02-24T14: 22: 50+00: 00
}
}
任何帮助将不胜感激。因为我正在尝试解决这个问题
更新 1
在下一行我收到错误:
User user = new Gson().fromJson(jsonResponse, User.class);
问题已经解决。我的下一步行动是: Instad 声明:
User user = new Gson().fromJson(jsonResponse, User.class);
我应该声明:
user = (User) apiUserResponse.getData();
// or
User user = (User) apiUserResponse.getData();
在其他情况下,您的 JSON 将被读取为格式错误并抛出异常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句