【发布时间】:2020-03-29 10:52:02
【问题描述】:
简而言之,问题是我有以下 HttpResponse 正文:
{"mammalList":[{"id":11,"details":{"id":3,"name":"Kangaroo","description":"Example",
"image":null},"age":40,"hasHooves":true,"hasPlacenta":false,"name":"Kangaroo"}]}
最后还有一个字段"name":"Kangaroo"
哺乳动物是:
Mammal(Long id, Details details, int age, boolean hasHooves, boolean hasPlacenta)
详细信息为Details(Long id, String name, String description, String image)
假设我有一个 Get 映射 animals/all/mammals
我有一个get方法,它首先创建一个HttpRequest
public static <E> E get(String path, Class<E> responseType) {
// Build HTTP request
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(host + "/" + path))
.setHeader("Content-Type", "application/json").GET().build();
然后尝试得到响应
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
/* 这是客户端 - private static final HttpClient client = HttpClient.newHttpClient(); */
使用 bean 和注释,我得到连接到 animals/all/mammals 的方法
并在方法结束时返回以下内容:
return ResponseEntity.ok(new MammalResponse(responseList));
(MammalResponse 是一个只包含哺乳动物列表、构造函数、getter 和 setter 的类)
方法末尾的调试器显示如下:(这是预期的)
responseList = {ArrayList@10790} size = 1
0 = {Mammal@10792}
age = 40
hasHooves = true
hasPlacenta = false
id = {Long@10793} 11
details = {Details@10794}
id = {Long@10795} 3
name = "Kangaroo"
description = "Example"
image = null
问题是,当我传递到 get 方法的下一行时,我有以下 HttpResponse 正文:
{"mammalList":[{"id":11,"details":{"id":3,"name":"Kangaroo","description":"Example",
"image":null},"age":40,"hasHooves":true,"hasPlacenta":false,"name":"Kangaroo"}]}
最后还有一个字段"name":"Kangaroo" Mammal 对象没有 name 属性,因此无法反序列化,一切都会走下坡路。
知道为什么它会在序列化的 Mammal 字符串的末尾添加那个额外的属性,以及如何阻止这种情况发生吗?
编辑:如果我将更多哺乳动物添加到数据库中,那么每个哺乳动物都会在哺乳动物列表中,其 Details 对象中的 name 也放在最后。
【问题讨论】:
-
你能告诉我们哺乳动物和细节对象吗?我想看看 htey 是否是实体,它们是否有任何映射关系
-
你有没有关于 mamal 类的吸气剂,比如 'getName()' - 如果有,这可能是原因
-
@ŢîganIon 是的!解决了它,非常感谢!
标签: java spring serialization httprequest httpresponse