提问者:小点点

杰克逊混合不工作


这是第三方类(为了示例起见,让我们假设)

public class User {
private Integer userId;
private String password;

public User(Integer userId, String password) {
    this.userId = userId;
    this.password = password;
}

public Integer getUserId() {
    return userId;
}

public String getPassword() {
    return password;
}

@Override
public String toString() {
    return "User [userId=" + userId + ", password=" + password + "]";
}
}

这里是对应的混音类

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public abstract class UserMixin {

@JsonProperty("userId")
abstract String getUserId();

@JsonProperty("password")
abstract String getPassword();

@JsonCreator
public UserMixin(
        @JsonProperty("userId") Integer userId
        , @JsonProperty("password") String password) {
    System.out.println("mixed-in constructor.");
}
}

这里是对应的驱动类

import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonMixIn {
public static void main(String[] args) throws IOException {

    User user = new User(1,  "password");

    ObjectMapper mapper = new ObjectMapper();
    final String json = mapper.writeValueAsString(user);
    System.out.println(json);

    ObjectMapper mapper2 = new ObjectMapper();
    mapper2.addMixIn(User.class, UserMixin.class);

    System.out.println(mapper2.writeValueAsString(user));

    final User deserializedUser = mapper2.readValue(json, User.class);
    System.out.println(deserializedUser);
}
}

如果我运行驱动程序类,每件事都像一个魅力,并获得预期的输出。

{"userId":1,"password":"password"}
{"userId":1,"password":"password"}
User [userId=1, password=password]

但是,如果我删除User类的以下getter

public Integer getUserId() {
   return userId;
}

public String getPassword() {
   return password;
}

我得到以下异常

在线程"main"com. fasterxml.jackson.datind.jsonMappingException中的异常:在com.fasterxml.jackson.datind.ser.iml.com.fasterxml.jackson.jsonMappingException.from(JsonMappingException.java:269)com.fasterxml.jackson.datind.ser.inpl.UnnovnSerializer.不知道的序列化程序(UnknownSerializer.java:68)在com.fasterxml.jackson.datind.ser.inpl.UnknownSerializer.java:32.DefaultSerializerProvider.序列化值(DefaultSerializerProvider.java:130)在com.fasterxml.jackson.datind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3631)在com.fasterxml.jackind.ObjectMapper


共1个答案

匿名用户

所有应该做的是以下和事情应该工作像一个魅力

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

有关更多详细信息,请参阅此