【发布时间】:2023-03-15 05:20:01
【问题描述】:
我正在使用RetrofitJackson2SpiceService 在服务中发出请求。 Jackson 用于解析来自 API 的 JSON 响应。
但我有一个问题。
我的User model 有以下声明
@JsonIgnoreProperties(ignoreUnknown=true)
public class User {
@JsonProperty("id")
public int id;
@JsonProperty("name")
public String name;
@JsonProperty("surname")
public String surname;
@JsonProperty("email")
public String email;
@JsonProperty("phone")
public String phone;
@JsonProperty("BirthDate")
public String birthDate;
@JsonProperty("token_model")
public Token token;
}
你可能注意到这个类有 Token 作为成员
@JsonIgnoreProperties(ignoreUnknown=true)
public class Token {
@JsonProperty("token")
public String token;
@JsonProperty("expiration_time")
public int expirationTime;
@JsonProperty("scope")
public int scope;
}
服务器响应如下所示
{"id":"36","email":"something@yo.com","name":"Say","surname":"hello","login":"superuser","phone":"4534333","token_model":{"token":"a220249b55eb700c27de780d040dea28","expiration_time":"1444673209","scope":"0"}}
令牌未被解析,它始终为空。
我尝试过手动转换字符串
String json = "{\"id\":\"36\",\"email\":\"something@yo.com\",\"name\":\"Say\",\"surname\":\"hello\",\"login\":\"superuser\",\"phone\":\"4534333\",\"token_model\":{\"token\":\"a220249b55eb700c27de780d040dea28\",\"expiration_time\":\"1444673209\",\"scope\":\"0\"}}";
ObjectMapper mapper = new ObjectMapper();
User user = null;
try {
user = mapper.readValue(json, User.class);
} catch (IOException e) {
e.printStackTrace();
}
而且它有效!令牌被正确解析,没有任何问题。
这里我使用了readValue方法接受String作为第一个参数,但是在Converter中
JavaType javaType = objectMapper.getTypeFactory().constructType(type);
return objectMapper.readValue(body.in(), javaType);
使用流版本的方法。
我尝试通过以下方式返回 Response 而不是 User 对象
public void onRequestSuccess(Response response) {
super.onRequestSuccess(response);
ObjectMapper objectMapper = new ObjectMapper();
User user = null;
try {
user = objectMapper.readValue(response.getBody().in(), User.class);
} catch (IOException e) {
e.printStackTrace();
}
}
而且它工作得很好,就像它应该的那样,令牌被正确解析。
我不知道什么会导致这样的问题,我尝试了很多不同的注释组合(自定义反序列化器、解包......)、自定义转换器但仍然相同。
如果有任何帮助,我将不胜感激。
谢谢。
【问题讨论】:
标签: java json jackson retrofit robospice