gpt4 book ai didi

Java Jersey JSON 服务不返回带引号的字符串?

转载 作者:行者123 更新时间:2023-12-03 23:56:15 26 4
gpt4 key购买 nike

这是一个使用 Jersey 编写的简单 Web 服务

@GET
@Produces(MediaType.APPLICATION_JSON)
public Object interpretationJson() {
String o = "a simple string";
return o;
}

对此的回应是:
HTTP/1.1 200
Content-Type: application/json
Content-Length: 15
Date: Mon, 02 Oct 2017 23:18:14 GMT

a simple string

响应正文中的字符串不应该被引用吗?我不相信这是有效的 JSON。响应不应该是:
HTTP/1.1 200
Content-Type: application/json
Content-Length: 15
Date: Mon, 02 Oct 2017 23:18:14 GMT

"a simple string"

这让我有些困惑。我原本以为问题出在客户端,但现在我认为问题是从 Jersey 返回的字符串无效 JSON - C# Parsing json that may have simple types

最佳答案

这是 Jackson 的开发人员 (Tatu Saloranta/cowtowncoder) 引用的关于为什么以这种方式处理简单字符串的引用。

This is not the reason String is declared untouchable. Rather, choice is between:

Write input String as JSON String, i.e. surround it with double-quotes and escape necessary characters, or

Write String exactly as-is, assuming user wanted to produce exactly that output (presumable hand-encoded JSON).

Since there is no metadata to tell what is user's intention, Jackson is being conservative and using latter choice. This is also prudent considering that JSON Specification only considers JSON Objects and JSON Arrays as valid JSON content -- so strictly speaking, returning a JSON String would produce invalid JSON anyway.



Referenced issue...

“不可触碰”是 jackson 对将完全按原样返回的类型的术语。

如果您愿意,您可以轻松地返回带引号的字符串,并且有多种方法可以做到这一点。但这不是你的问题,我想。

关于Java Jersey JSON 服务不返回带引号的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46535586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com