Java Jersey JSON服务不返回带引号的字符串吗? [英] Java Jersey JSON service doesn't return quoted string?

查看:194
本文介绍了Java Jersey JSON服务不返回带引号的字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is a simple Web Service written using Jersey

@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.响应不应该是:

Shouldn't the string in the response body be quoted? I don't believe this is valid JSON. Shouldn't the response be:

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-

This caused me a bit of confusion. I originally thought the problem was on the client side, but now I think the problem is the string returned from Jersey is not valid JSON - C# Parsing json that may have simple types

推荐答案

此处引述了杰克逊开发人员(Tatu Saloranta/cowtowncoder)关于为什么这样处理简单字符串的引用.

Here is a quote attributed to Jackson's developer (Tatu Saloranta / cowtowncoder) about why a simple string is treated this way.

这不是将String声明为不可触摸的原因.相反,选择是 之间:

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

将输入字符串写为JSON字符串,即用双引号将其括起来 并转义必要的字符,或者

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

完全照原样编写String,假设用户想精确地产生该字符串 输出(大概手工编码的JSON).

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

由于没有元数据可以说明用户的意图,因此杰克逊 保守一点,使用后一种选择. 考虑到JSON规范仅考虑了这一点也是谨慎的 JSON对象和JSON数组作为有效的JSON内容-严格来说, 无论如何,返回JSON字符串都会产生无效的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.

参考问题...

不可触碰"是杰克逊(Jackson)所指的一种类型,该类型将完全按原样返回.

"Untouchable" is Jackson's term for a type that will be returned exactly as is.

如果需要,您可以轻松地返回带引号的字符串,并且有几种方法可以使用它.我想那不是你的问题.

You can easily return a string with quotes if you want to and there are several ways to do it. But that was not your question, I think.

这篇关于Java Jersey JSON服务不返回带引号的字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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