gpt4 book ai didi

java - 无法从 json 中读取 URL 字符串并将其应用于 Android 中的对象

转载 作者:行者123 更新时间:2023-11-30 00:37:37 24 4
gpt4 key购买 nike

我正在构建一个应用程序并有一个 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{} 后进入第一行之后 - 它崩溃了,下一个错误出现在日志中:

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);

最佳答案

问题已经解决。接下来是我的行动:代替声明:

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

我应该声明:

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

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

关于java - 无法从 json 中读取 URL 字符串并将其应用于 Android 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43150402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com