我在Spring Boot中有一个RestController示例:

@RestController
@RequestMapping("/api")
class MyRestController
{
    @GetMapping(path = "/hello")
    public JSONObject sayHello()
    {
        return new JSONObject("{'aa':'bb'}");
    }
}

I am using the JSON library org.json

当我点击API /hello时,我收到一个异常,说:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is JAVAlang.IllegalArgumentException:未找到要返回的转换器] with root cause

JAVAlang.IllegalArgumentException:未找到要返回的转换器

What is the issue? Can someone explain what exactly is happening?

推荐答案

当您使用Spring Boot web时,Jackson依赖关系是隐式的,我们不必显式定义.如果使用eclipse,可以在dependency hierarchy选项卡的pom.xml中判断Jackson依赖关系.

And as you have annotated with @RestController there is no need to do explicit json conversion. Just return a POJO and jackson serializer will take care of converting to json. It is equivalent to using @ResponseBody when used with @Controller. Rather than placing @ResponseBody on every controller method we place @RestController instead of vanilla @Controller and @ResponseBody by default is applied on all resources in that controller.
Refer this link: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

The problem you are facing is because the returned object(JSONObject) does not have getter for certain properties. And your intention is not to serialize this JSONObject but instead to serialize a POJO. So just return the POJO.
Refer this link: https://stackoverflow.com/a/35822500/5039001

If you want to return a json serialized string then just return the string. Spring will use StringHttpMessageConverter instead of JSON converter in this case.

Json相关问答推荐

震击:三针并用震击

Oracle plsql:如何将json文件加载到嵌套表中

从Postgres表中的JSON中提取值

XSLT 3.0 Json-to-xml,json 包含 html struct

删除 JOLT 中的方括号

Jolt 规范将父对象中的所有键应用于数组中的所有对象

根据数据框中的其他列值将列表 json 对象插入行

向 JSON 文件添加注释

序列化特定类型时如何使 JSON.Net 序列化程序调用 ToString()?

为什么在我们有 json_encode 时使用 CJSON 编码

Retrofit 2.0 如何解析嵌套的 JSON 对象?

没有很多类的 GSON 解析

如何在 Eclipse 中安装和使用 JSON 编辑器?

Golang struct 的 XML 和 JSON 标签?

如何在 Rails 模型中验证字符串是否为 json

将序列化表单的数据转换为 json 对象

ASP.NET Web API JSON 输出中没有时间的日期

将多个值存储在json中的单个键中

如何使用 SwiftyJSON 遍历 JSON?

无法将 System.String 转换或转换为 Class 对象