首页 > 解决方案 > 如何告诉杰克逊在反序列化时忽略某些字段

问题描述

我正在调用一个端点,它在其中返回一个对象。在这个对象中,它包含一些字段以及另一种对象的字段。例如

class ResponseObject{
private final boolean success;
private final String message;    
private final DifferentType different;
}

我通过 RestTemplate 调用端点:

   private LogonResponseMessage isMemberAuthenticated(UserCredentialDomain userCredentialDomain)
   {
      RestTemplate restTemplate = new RestTemplate();
      return restTemplate.getForObject(
         "http://abc.local:8145/xyz/member/authenticate/{memberLoginName}/{password}", ResponseObject.class,
         userCredentialDomain.getUsername(), userCredentialDomain.getPassword());
   }

所以我的消费应用程序给出了这个错误:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `fgh.thg.member.DifferentTypeABC` (no Creators, like default constructor, exist): cannot deserialize from Object v
alue (no delegate- or property-based Creator)

我知道它告诉我在 DifferentTypeABC 类中放置一个默认构造函数,以便让杰克逊反序列化它,但我不能轻易做到这一点,因为我需要更新对不同类型ABC 所在应用程序的依赖关系。回购。

所以我想知道是否有一种方法可以在消费应用程序上配置 RestTemplate 或 jackson,以便如果它不包含默认构造函数,它会忽略尝试反序列化对象?老实说,我对响应对象上的successandmessage字段非常感兴趣。

标签: javaspringspring-bootjackson

解决方案


解决问题的另一种方法是DifferentType在此模块中使用Jackson creator Mixin. 下面是一个例子:

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.io.IOException;

public class Test {

  public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    mapper.setVisibility(mapper.getVisibilityChecker()
        .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
        .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
        .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
        .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

    mapper.addMixIn(DifferentType.class, DifferentTypeMixin.class);
    String raw = "{\"message\": \"ok\", \"differentType\": {\"name\": \"foo bar\"}}";
    ResponseObject object = mapper.readValue(raw, ResponseObject.class);
    System.out.println(mapper.writeValueAsString(object));
  }

  @Data
  static class ResponseObject {
    private String message;
    private DifferentType differentType;
  }

  static class DifferentType {
    private String name;

    public DifferentType(String name) {
      this.name = name;
    }
  }

  public static abstract class DifferentTypeMixin {
    @JsonCreator
    DifferentTypeMixin(@JsonProperty("name") String name) {
    }
  }
}

推荐阅读