【问题标题】:Spring controller inheritance and linked requestbody deserealization problemsSpring控制器继承和链接requestbody解散问题
【发布时间】:2021-10-05 11:27:26
【问题描述】:

当我使用 spring 控制器和类进行 requestbody 继承时,我的 objectmapper 不工作。

 @JsonTypeInfo(
            use = JsonTypeInfo.Id.NAME,
            include = JsonTypeInfo.As.PROPERTY,
            property = "type", visible = true)
    @JsonSubTypes({
            @JsonSubTypes.Type(value = RecipeVersion.class, name = "recipe"),
            @JsonSubTypes.Type(value = DietVersion.class, name = "diet"),
    })
    public interface DocumentVersion {
        Info getInfo();
        void setInfo(Info info);
    }

还有

@Data
public class DietVersion implements DocumentVersion {
    private LocalizedText warnings;
    private List<DietDay> days = new LinkedList<>();
    private Info info = new Info();

    private String getType() {
        return "diet";
    }
}

好的。我有用于饮食和食谱的 BaseController

abstract public class BaseController<T extends Document<V>, V extends DocumentVersion> {

    abstract protected BaseService<T, V> getService();

    @PostMapping("/{docId}/version/last")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void saveVersion(@PathVariable("docId") String docId, @RequestBody V version, Authentication authentication) {
        getService().replaceLastVersion(docId, version, authentication);
    }
}

还有一些认识。饮食举例

@Controller
@RequestMapping("/diet")
public class DietController extends BaseController<Diet, DietVersion> {

    private final DietService dietService;

    @Autowired
    public DietController(DietService dietService) {
        this.dietService = dietService;
    }

    @Override
    protected DietService getService() {
        return dietService;
    }

    @Override
    public void saveVersion(String docId, DietVersion version, Authentication authentication) {
        super.saveVersion(docId, version, authentication);
    }
}

但是当我发送带有信息、天数的 json 时,输入 ('diet') 到 '/diet/1/version/last' 然后我在调试模式下看到我的 DietVersion 完全清晰并且没有任何数据。为什么?

如何更改对象映射器的设置?

【问题讨论】:

  • 如果你在 DietController 类中提供所有这些会怎样。 public void saveVersion(@PathVariable("docId") String docId, @RequestBody V version, Authentication authentication){
  • @yas 做出回答。我将其标记为解决方案

标签: spring-mvc jackson-databind


【解决方案1】:

如果您在 DietController 类中提供所有这些内容会怎样。

public void saveVersion(@PathVariable("docId") String docId, @RequestBody V version, Authentication authentication){

【讨论】:

  • 2 个变体:a) 从 DietController 中删除 saveVersionMethod b) 添加 pathVariable 并请求正文注释 - 一切正常!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-17
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多