Spring @ResponseBody为原始类型生成无效的JSON [英] Spring @ResponseBody produces an invalid JSON for primitive types

查看:320
本文介绍了Spring @ResponseBody为原始类型生成无效的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自REST API的代码,它使用 @ResponseBody 来返回结果,并使用 MappingJacksonHttpMessageConverter 来以JSON格式返回。

I have a code from a REST API which uses @ResponseBody to return the result, and a MappingJacksonHttpMessageConverter to return it in a JSON format.

这一切都适用于复杂的对象。
对于 int boolean string 我得到的JSON不是以{或[。
这不是一个有效的JSON。

It all works well for complex objects. For primitives like int, boolean and string I get a JSON which does not start with { or [. This is not a valid JSON.

我想知道返回这样一个简单类型的正确方法是什么?
我应该将它封装在一个对象中,例如 {Result:true}

I was wondering what is the proper way to return just a simple type like that? Should I encapsulate it in an object such as { Result : true } ?

谢谢

代码示例:

@RequestMapping(
        value = "/login",
        method = RequestMethod.POST)
@ResponseBody
public boolean Login(String username, String password) {
    return authenticationService.authenticate(username, password);
}

这将只返回 true false 这是一个无效的JSON。它应该被封装在一个对象或一个数组中(如果我理解的话)。

This will return just true or false which is an invalid JSON. It should either be encapsulated in an object or an array (if I understand correctly).

推荐答案

它只返回true,或者假。而你是正确的不是json。

It does just return true, or false. And you are correct that is not json.

它不能是json,因为它不是一个对象,它只是一个原语,所以它很好 - 它将被分配给你成功的javascript变量处理程序。

It can't be json because its not an object, it is simply a primitive, so its fine as is - it will be assigned to a javascript variable in your success handler.

如果你返回一个布尔列表,你会得到一个数组:

If you return a list of Booleans you get an array :

[true,false,true]

如果你必须完全形成json,则不返回原语使用散列映射或自定义包装器对象。

If you must have fully formed json don't return a primitive use a hashmap or custom wrapper object.

public
@ResponseBody
Map<String, Boolean> getTrue() {
  Map<String, Boolean> map = new HashMap<String, Boolean>(1){{put("result", Boolean.TRUE);}};
  return map;
}

返回hashmap可能是获取所需json的最简单,最好的方法:

Returning a hashmap is probably the simplest and best way to get the json you require :

{"result":true}

这篇关于Spring @ResponseBody为原始类型生成无效的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆