Spring引导 - json post请求body作为POJO和string

时间:2018-03-07 06:17:57

标签: java spring spring-boot

在spring boot controller方法中,我可以将json post请求体映射到POJO,例如

@PostMapping(value = "/abc")
public String handleABC(
        @RequestBody User user
) {
    //code here...
}

我还可以将原始请求正文检索为字符串:

@PostMapping(value = "/abc")
public String handleABC(
        @RequestBody String request
) {
    //code here...
}

我的问题是如何将请求主体映射到POJO并将原始请求主体检索为字符串(用于记录目的)。

谢谢

2 个答案:

答案 0 :(得分:0)

通常,SpringBoot默认使用Jackson作为序列化框架。

如果没有效果,您可以检查您的配置,并继承WebMvcConfigurerAdapter重写configureMessageConverters序列化方法和特定行为。

像这样:

I use FastJson as serialization framework, You can set up Jackson's configuration here instead of doing it like I did.

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    /**
     * custom MessageConverter
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter4 converter = new FastJsonHttpMessageConverter4();
        FastJsonConfig config = new FastJsonConfig();
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        converters.add(converter);
    }
}

答案 1 :(得分:0)

这应该有效

builder.CreateFile("pptx");
var oPresentation = Api.GetPresentation();
var oParagraphCell, oTable, oTableStyle, oCell, oTableRow, oParagraph;
var oSlide = oPresentation.GetSlideByIndex(0);
oSlide.RemoveAllObjects();
var oShape = Api.CreateShape("rect", 300 * 36000, 130 * 36000, oFill, oStroke);
oShape.SetPosition(608400, 1267200);
oDocContent = oShape.GetDocContent();
oParagraph = oDocContent.GetElement(0);
oParagraph.AddText("This is an example of the ppt.");
oParagraph = Api.CreateParagraph();
oDocContent.InsertContent([oParagraph]);
oTableStyle = oDocContent.CreateStyle("CustomTableStyle", "table");
oTableStyle.SetBasedOn(oDocument.GetStyle("Bordered - Accent 5"));
oTable = Api.CreateTable(3, 3);
oTable.SetWidth("percent", 100);
oTableRow = oTable.GetRow(0);
oTableRow.SetHeight("atLeast", 1440);
oCell = oTable.GetRow(0).GetCell(0);
oCell.SetVerticalAlign("top");
oParagraphCell = oCell.GetContent().GetElement(0);
oParagraphCell.AddText("Align top");
oCell = oTable.GetRow(0).GetCell(1);
oCell.SetVerticalAlign("center");
oParagraphCell = oCell.GetContent().GetElement(0);
oParagraphCell.AddText("Align center");
oCell = oTable.GetRow(0).GetCell(2);
oCell.SetVerticalAlign("bottom");
oParagraphCell = oCell.GetContent().GetElement(0);
oParagraphCell.AddText("Align bottom");
oTable.SetStyle(oTableStyle);
oDocContent.InsertContent([oTable]);
oSlide.AddObject(oShape);
builder.SaveFile("pptx", "SampleText.pptx");
builder.CloseFile();