如何告诉jackson在反序列化时忽略某些字段

q8l4jmvw  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(610)

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

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)

我知道它告诉我在differenttype类中放置一个默认构造函数,以便jackson反序列化它,但我不能这么做,因为我需要更新不同类型在几个不同repo中对应用程序的依赖关系。
因此,我想知道是否有一种方法可以在消费应用程序上配置restemplate或jackson,以便在不包含默认构造函数的情况下忽略反序列化对象的尝试?老实说,我对 success 以及 message 响应对象上的字段。

5cnsuln7

5cnsuln71#

解决这个问题的另一个方法是加强 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) {
    }
  }
}

相关问题