繁体   English   中英

杰克逊自定义解串器在春季启动中无法正常工作

[英]Jackson Custom Deserializer Not Working In Spring Boot

我为我的实体创建了一个自定义反序列化器,但不断抛出异常:

我有两个类:AppUser和AppUserAvatar

AppUser.java

@Entity
@Table(name = "user")
public class AppUser implements Serializable {

    @Transient
    private static final long serialVersionUID = -3536455219051825651L;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Column(name = "password", nullable = false, length = 256)
    private String password;

    @JsonIgnore
    @Column(name = "is_active", nullable = false)
    private boolean active;

    @JsonIgnore
    @OneToMany(mappedBy = "appUser", targetEntity = AppUserAvatar.class, fetch = FetchType.LAZY)
    private List<AppUserAvatar> appUserAvatars;

    //// Getters and Setters and toString() ////
}

AppUserAvatar.java

@Entity
@Table(name = "user_avatar")
public class AppUserAvatar extends BaseEntityD implements Serializable {

    @Transient
    private static final long serialVersionUID = 8992425872747011681L;

    @Column(name = "avatar", nullable = false)
    @Digits(integer = 20, fraction = 0)
    @NotEmpty
    private Long avatar;

    @JsonDeserialize(using = AppUserDeserializer.class)
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false)
    private AppUser appUser;

    //// Getters and Setters and toString() ////
}

AppUserDeserializer.java包com.nk.accountservice.deserializer;

import com.edoctar.accountservice.config.exception.InputNotFoundException;
import com.edoctar.accountservice.domain.candidate.AppUser;
import com.edoctar.accountservice.service.candidate.AppUserService;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.Serializable;

public class AppUserDeserializer extends JsonDeserializer implements Serializable {

    private static final long serialVersionUID = -9012464195937554378L;

    private AppUserService appUserService;

    @Autowired
    public void setAppUserService(AppUserService appUserService) {
        this.appUserService = appUserService;
    }

    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        Long userId = node.asLong();
        System.out.println(node);
        System.out.println(node.asLong());
        AppUser appUser = appUserService.findById(userId);
        System.out.println("appuser: " + appUser);
        if (appUser == null) try {
            throw new InputNotFoundException("User not found!");
        } catch (InputNotFoundException e) {
            e.printStackTrace();
            return null;
        }

        return appUser;
    }
}

示例xhr男孩是:

{
  "appUser": 1,
  "avatar": 1
}

每次我提交请求时都会引发异常。

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: (was java.lang.NullPointerException); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.edoctar.accountservice.domain.candidate.AppUserAvatar["appUser"])]

这是我的控制台的屏幕截图。

我发现没有调用appUserService.findById()方法。 我真的很困惑。 我不知道哪里出了问题。 任何解决方案都将非常有用。 谢谢。

更新的答案:您不能使用自动装配的属性,因为您不在Spring上下文中。 您正在传递类AppUserDeserializer作为注释中的引用

@JsonDeserialize(using = AppUserDeserializer.class)

在这种情况下是FasterJackson库创建的实例AppUserDeserializer ,所以Autowired注解不考虑拍摄。

您可以通过一点技巧解决问题。 AppUserService添加对spring创建的实例的静态引用:

 @Service
 public AppUserService {

   public static AppUserService instance;

   public AppUserService() {
     // Modify the constructor setting a static variable holding a
     // reference to the instance created by spring
     AppUserService.instance = this;
   }

   ...
 }

AppUserDeserializer使用该引用:

public class AppUserDeserializer extends JsonDeserializer implements Serializable {

    private AppUserService appUserService;

    public AppUserDeserializer() {
      // Set appUserService to the instance created by spring
      this.appUserService = AppUserService.instance;
    }

    ...

}

原始答案:若要正确初始化Autowired属性,必须注释类AppUserDeserializer ,否则,如果未使用set方法显式初始化它,则appUserService为null。

尝试使用@Component注释AppUserDeserializer

@Component   // Add this annotation
public class AppUserDeserializer extends JsonDeserializer implements Serializable {
   ...
}

尝试更改以下代码行:

private boolean active;

private Boolean active;

布尔原语不能处理空值,并且可能导致NPE。

您可以继续尝试正确注入AppUserService但是根据我的说法,这不是最干净的解决方案。 通常,我不喜欢将@Entity用作通信模型或视图模型的想法。 通过这种方式,您可以将实体耦合到视图模型的生产者/消费者。 您基本上是在短路模型零件。

我要做的是在反序列化阶段将json的内容映射到另一个类,并在以后使用它构造相应的实体。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM