无法从json读取URL字符串并将其应用于Android中的Object

时间:2017-03-31 22:09:28

标签: java android json url

我正在构建一个应用程序,并且有一个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();
                }
            }

在尝试{}之后步进到第一行之后 - 它崩溃并且下一个错误在日志中出现:

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=test@email.com,
    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
    }
}

任何帮助将不胜感激。因为我正试图解决这个问题

UPD 1

在下一行我收到错误:

User user = new Gson().fromJson(jsonResponse, User.class);

1 个答案:

答案 0 :(得分:1)

问题已经解决了。我的行动是下一步: 声明的内容:

User user = new Gson().fromJson(jsonResponse, User.class);

我应该声明:

user = (User) apiUserResponse.getData();
// or
User user = (User) apiUserResponse.getData();

在其他情况下,您的JSON将被视为格式错误,并且会抛出异常。