3

我正在尝试使用杰克逊序列化对象层次结构,但我必须在每个控制器方法中使用不同的字段。目前,我这样做:

@RequestMapping(value = "/chat/message/create",
            headers = "Accept=application/json", 
            produces = MediaType.APPLICATION_JSON_VALUE, 
            method = RequestMethod.GET
            )
    @Transactional
    public @ResponseBody
    ChatMessage createChatMessage(@RequestParam("chat_id") Integer chatId, 
            @RequestParam("chat_from_id") Integer chatFromId,
            @RequestParam("chat_content") String content) {

        User fromUser = userDAO.find(User.class, chatFromId);

        ChatMessage message = new ChatMessage();
        message.setContent(content);
        message.setLastUpdateDate(new Date());
        message.setFromUser(fromUser);

        Chat chat = chatDAO.find(Chat.class, chatId);
        message.setChat(chat);

        chatMessageDAO.save(message);

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        FilterProvider filters = new SimpleFilterProvider()
            .addFilter("chatMessageFilter", SimpleBeanPropertyFilter.serializeAllExcept(Collections.EMPTY_SET));
        ObjectWriter writer = mapper.writer(filters);
        try {
            return writer.writeValueAsString(message);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

问题是我想使用 MappingJackson2HttpMessageConverter,但我找不到在其上设置 beanpropertyfilters 列表的过滤器提供程序的方法。我想做这样的事情:

@RequestMapping(value = "/chat/message/create",
            headers = "Accept=application/json", 
            produces = MediaType.APPLICATION_JSON_VALUE, 
            method = RequestMethod.GET
            )
    @Transactional
    public @ResponseBody
    ChatMessage createChatMessage(@RequestParam("chat_id") Integer chatId, 
            @RequestParam("chat_from_id") Integer chatFromId,
            @RequestParam("chat_content") String content) {

        User fromUser = userDAO.find(User.class, chatFromId);

        ChatMessage message = new ChatMessage();
        message.setContent(content);
        message.setLastUpdateDate(new Date());
        message.setFromUser(fromUser);

        Chat chat = chatDAO.find(Chat.class, chatId);
        message.setChat(chat);

        chatMessageDAO.save(message);

        getFilterProvider().addFilter("chatMessageFilter", SimpleBeanPropertyFilter.serializeAllExcept(Collections.EMPTY_SET));

        return message;
    }

getFilterProvider() 将获取 MappingJackson2HttpMessageConverter 使用的 FilterProvider。这样,我会在一种方法中设置 5 或 6 个过滤器,在另一种方法中设置完全不同的过滤器。

注意:Json 视图在这里对我没有帮助。它们太静态了,我无法组合指定用于嵌套对象的视图。

4

0 回答 0