春季靴子 - gson singleton?

时间:2015-10-26 06:28:36

标签: java spring spring-mvc spring-boot

我的应用程序目前运行的是Gson而不是jackson,如何使用gson解析传入的表单提交?

我目前正在

  

2015-10-26 14:14:59.027 ERROR 12876 --- [nio-8080-exec-1] com.exp.controllers.UserController:Bean对象不能为null;嵌套异常是java.lang.IllegalArgumentException:Bean对象不能为null

@RestController
public class UserController {

    @Autowired
    private UserDao userDao;

    @Autowired
    private GsonHttp gsonHttp;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

  @RequestMapping(value="/createPOST", method = RequestMethod.POST)
  @ResponseBody
  public ResponseData createPOST(String json) {
    User user = null;
    try {
      user = gsonHttp.getGson().fromJson(json, User.class);
      userDao.save(user);
    }
    catch (Exception ex) {
        log.error(ex.getMessage());
        return new ResponseData(false, Arrays.asList("Error with user creation."));
    }
    return new ResponseData(true, Arrays.asList(user));
  }
}

用这个:

@Repository
public class GsonHttp {

    private Gson gson;

    public GsonHttp(){
        this.gson = new Gson();
    }

    public Gson getGson() {
        return gson;
    }

    public void setGson(Gson gson) {
        this.gson = gson;
    }

}

1 个答案:

答案 0 :(得分:4)

" Bean对象不能为空"当您尝试保存空对象时,存储库会抛出该文件。

userDao.save(user) //User is null

您的对象为空的原因是因为您无法在不添加@RequestBody的情况下获取json,因此请更改您的json参数以使其具有此注释

public String createPost(@RequestBody String json) { //Added @RequestBody

在Spring Boot中设置GSON

默认情况下,杰克逊是默认解析器,正如您所解释的那样,用GSON替换它很容易。

的src /主/资源/ application.properties

  

spring.http.converters.preferred-JSON-mapper.gson =真

这显然需要类路径上的GSON。

然后重写你的创建帖子方法

  @RequestMapping(value="/createPOST", method = RequestMethod.POST)
  @ResponseBody
  public ResponseData createPOST(@RequestBody User user) {
    userDao.save(user);
    return new ResponseData(true, Arrays.asList(user));
  }
  

基础HTTPMessageConverterClass - https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/HttpMessageConvertersAutoConfiguration.java

-

  

Gson特定配置 - https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/GsonHttpMessageConvertersConfiguration.java

请务必特别注意最后一个源中的PreferGsonOrMissingJacksonCondition类。它使用GSON,如果gson配置为首选,或者Gson是在类路径上而jackson不是(例如,如果你将它从Maven或Gradle中排除)