为了将空字符串转换为“”,引入了FastJsonHttpMessageConverter。 Controller 定义为:
定义的请求模型为:enter image description here 。 而FastJsonHttpMessageConverter的配置为: configuration of FastjsonHttpMessageConvert 当我使用如下请求体调用 Controller 时: request body .
响应是:错误请求:JSON 解析错误:null;嵌套异常为 com.alibaba.fastjson.JSONException。
不知道如何解决,希望得到有用的帮助! 非常感谢!
最佳答案
我建议使用mapstruct作为映射器,这里是一个例子:
1) 将依赖项和插件添加到您的 pom 中: -> 插件:
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.0.Final</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
<compilerArg>
-Amapstruct.defaultComponentModel=spring
</compilerArg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<version>2.2.4</version>
<configuration>
<defaultOutputDirectory>
${project.build.directory}/generated-sources
</defaultOutputDirectory>
<processors>
<processor>org.mapstruct.ap.MappingProcessor</processor>
</processors>
</configuration>
<executions>
<execution>
<id>process</id>
<phase>generate-sources</phase>
<goals>
<goal>process</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.0.0.Final</version>
</dependency>
</dependencies>
</plugin>
</plugins>
---> 依赖关系:
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.1.0.Final</version>
</dependency>
---> Pojo 示例:
public class TestPojo{
private String test1;
private String test2;
//getter and setter ....
}
--> 创建您自己的通用映射器接口(interface):
public interface PojoMapper<D,P>{
P toPojo(D paramterfromRequest);
}
---> 创建通用接口(interface)的实现:
@Mapper
public interface PojoMapper extends PojoMapper<RequestObject, TestPojo>{
@Override
default TestPojo toPojo(RequestObject requestObject){
if(requestObject == null)
return null;
else {
TestPojo test = new TestPojo();
requestObject.getStringTarget() == null ? test.settest1("") : test.settest1(requestObject.getStringTarget());
requestObject.getStringTarget2() == null ? test.settest2("") : test.settest2(requestObject.getStringTarget2());
return test;
}
}
}
希望这对您或任何其他人有帮助:)
关于java - JSON解析错误: null; nested exception is com. alibaba.fastjson.JSONException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58165696/