Spring @ResponseBody为原始类型生成无效的JSON

编程入门 行业动态 更新时间:2024-10-28 11:21:23
本文介绍了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

本文发布于:2023-11-26 04:48:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632691.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原始   类型   Spring   ResponseBody   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!