我有以下响应:
{
"data": "[{"{Test}.id":12984,"{Test}.url":"https://login.test.com/0010b00002CIwX5AAL"},{"{Test}.id":84592,"{Test}.url":""}]"
}
我试图通过JSON到Java对象反序列化与转义属性来解决它,但看起来我做错了什么,或者没有正确理解如何使用这种方法,因为我在数据对象中得到一个空列表。
public class Wrapper {
@JsonProperty("data")
@JsonDeserialize(using = ProviderResponseDeserializer.class)
private List<TestObject> data;
}
public class TestObject{
@JsonProperty("{Test}.id")
public Integer id;
@JsonProperty("{Test}.url")
public String url;
}
public class ProviderResponseDeserializer extends JsonDeserializer<List<TestObject>> {
private static final ObjectMapper mapper = new ObjectMapper();
@Override
public List<TestObject> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
return mapper.readValue(jsonParser.getText(), mapper.getTypeFactory().constructCollectionType(List.class, TestObject.class));
}
}
你能帮我解决我做错的地方或建议其他方法吗?
这是你在问题中给出的相同代码,它正常工作。
public class Main {
public static void main(String[] args) throws IOException {
String s = "{"data":"[{\"{Test}.id\":12984,\"{Test}.url\":\"https://login.test.com/0010b00002CIwX5AAL\"},{\"{Test}.id\":84592,\"{Test}.url\":\"\"}]"}";
ObjectMapper objectMapper = new ObjectMapper();
Wrapper wrapper = objectMapper.readValue(s, Wrapper.class);
wrapper.getData().forEach(System.out::println);
}
}
@Getter
@Setter
class Wrapper {
@JsonProperty("data")
@JsonDeserialize(using = ProviderResponseDeserializer.class)
private List<TestObject> data;
}
@Getter
@Setter
@ToString
class TestObject{
@JsonProperty("{Test}.id")
private Integer id;
@JsonProperty("{Test}.url")
private String url;
}
class ProviderResponseDeserializer extends JsonDeserializer<List<TestObject>> {
private static final ObjectMapper mapper = new ObjectMapper();
@Override
public List<TestObject> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
return mapper.readValue(jsonParser.getText(), mapper.getTypeFactory().constructCollectionType(List.class, TestObject.class));
}
}
输出TestObject(id=12984, url=https://login.test.com/0010b00002CIwX5AAL)
TestObject(id=84592, url=)