如何在spring-boot中注册自定义HttpMessageConvertor?

时间:2016-02-19 10:30:41

标签: spring spring-mvc spring-boot

我正在使用spring-boot REST服务,它需要将传入的json字段转换为自定义实体。但我无法使自定义转换器工作。

我确信我错过了一些非常明显的东西,但无法弄清楚是什么!

我有以下JSON,我想将其转换为Item Entity

{
    'item_name':'some item name',
    'item_category':'some item catagory',
    'status_date_flag':'T',
    'item_sale_date':'2015-10-28' 
} 

物品实体

class Item{

    private String itemName;
    private String catagory;
    private boolean isDateFlagOn;
    private LocalDate saleDate;

    //...
    //public getters/setters
}

我创建了一个自定义消息转换器

@Component
public class ItemMessageConverter extends AbstractHttpMessageConverter<Item> {

    public ProductMessageConverter() {
        super(MediaType.ALL);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return clazz.getSimpleName().equalsIgnoreCase(Item.class.getSimpleName());
    }

    @Override
    protected Product readInternal(Class<? extends Item> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
         System.out.println("readInternal GETTING called......................");

        return null;
    }

    @Override
    protected void writeInternal(Product product, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        System.out.println("writeInternal GETTING called......................");
    }
}

我已经创建了一个用于注册HttpMessageConverter

的配置类
@Configuration
public class MyBootConfiguration {
    @Bean public HttpMessageConverters customConverters(){
        HttpMessageConverter itemMessageConverter = new ItemMessageConverter();
        return new HttpMessageConverters(itemMessageConverter);
    }

}

1 个答案:

答案 0 :(得分:1)

您尝试做的是通过自定义Jackson转换器实现的。像这样更改Item类定义:

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

@JsonDeserialize(using = ItemDeserializer.class)
public class Item {
    private String itemName;
    private String category;
    private boolean isDateFlagOn;
//constructor, getters and setters
}

注释表明这个类应该通过ItemDeserializer反序列化,这里是它的实现:

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 java.io.IOException;
import java.util.Objects;

public class ItemDeserializer extends JsonDeserializer {
    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        String itemName = node.get("itemName").textValue();
        String category = node.get("category").textValue();
        String flagStr = node.get("isDateFlagOn").textValue();

        return new Item(itemName, category, Objects.equals(flagStr, "T"));
    }
}

此代码在Spring 4.2中使用以下处理程序正常工作:

@Controller
public class GreetingController {
    @RequestMapping("jsonGreeting")
    public ResponseEntity jsonGreeting(@RequestBody Item item, BindingResult result) throws Exception {
        if (result.hasErrors()){
            return ResponseEntity.badRequest().body("parse error: " + result.getAllErrors().toString());
        }
        return ResponseEntity.ok(item.toString());
    }
}