【问题标题】:Java Spring - The HttpClient assigns an extra field when serializing a ResponseEntityJava Spring - 序列化 ResponseEntity 时 HttpClient 分配一个额外的字段
【发布时间】: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


【解决方案1】:

您对调用“哪个服务”以获取 HTTPResponse 的描述远未完成。是你自己的服务吗?

在任何情况下,快速解决方法是使用 @JsonIgnoreProperties 注释您的 Mammal 类。

import com.fasterxml.jackson.annotation.JsonIgnoreProperties

@JsonIgnoreProperties
class { ... }

使用该注释,未知字段将不再使您的程序“走下坡路”。

【讨论】:

    【解决方案2】:

    感谢@Ţîgan Ion,它已修复!

    我在 Mammal 中有一个 getName() 方法,这就是名称被输入两次的原因。当我将其注释掉时,从数据库中获取哺乳动物按预期工作。

    再次感谢@Ţîgan Ion。如果您将其写为答案,我会将其标记为正确的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-02
      • 2022-08-08
      • 2021-10-19
      • 2015-09-01
      相关资源
      最近更新 更多