Springboot json没有默认构造函数的模型

时间:2015-11-27 13:08:59

标签: json spring spring-boot

我遇到了问题,我无法弄清楚。

上下文

我有一个控制器:

@RestController
@RequestMapping("/classroom")
public class ClassroomController {

    @Inject
    private ClassroomManager classroomManager;

    @RequestMapping(value= "", method = RequestMethod.POST)
    public Classroom create(Classroom classroom) {
        ... some checks ...
        return classroomManager.create(classroom);
    }
}

模型类:

public class Classroom {

    private Long id;
    private final String name;
    private final RoomCapacity roomCapacity;
    private final Set<RoomEquipment> equipments = new HashSet<>();
    [... No setter, No default constructor ...]



    public Classroom(String name, RoomCapacity roomCapacity) {
        [... some checks ...]
        this.name = name;
        this.roomCapacity = roomCapacity;
    }
}

问题是,我无法使用Classroom作为JSON发送POST请求。

当我这样做时,我遇到了这个例外:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.ubp.ent.backend.core.model.classroom.Classroom]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.ubp.ent.backend.core.model.classroom.Classroom.<init>()

我的问题是什么

我理解错误,我可能会在类中添加一个默认构造函数 但Classroom点来自模型,我不想允许默认实例化。

如何让Spring能够从Json构建?

2 个答案:

答案 0 :(得分:1)

您需要使用HttpMessageConverter,并将参数作为@RequestBody接收。

@RequestMapping(value= "", method = RequestMethod.POST)
public Classroom create(@RequestBodyClassroom classroom) {
    ... some checks ...
    return classroomManager.create(classroom);
}

public class ClassroomConverter extends AbstractHttpMessageConverter<Classroom> {
...
}


@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> httpMessageConverters) {
        httpMessageConverters.add(new ClassroomConverter(new MediaType("text", "csv")));
    }
}

这里有一个类似于你的案例

http://www.beabetterdeveloper.com/2013/07/spring-mvc-requestbody-and-responsebody.html

答案 1 :(得分:1)

您可以通过为您的模型类定义Jackson自定义反序列化器来完成此操作。 请查看以下链接,了解如何实施和配置它。

http://wiki.fasterxml.com/JacksonHowToCustomDeserializers

http://www.baeldung.com/jackson-deserialization