JAX-RS(泽西岛):JSON请求正文中的字符串仍然转义 [英] JAX-RS (Jersey): String from JSON request body still escaped

查看:190
本文介绍了JAX-RS(泽西岛):JSON请求正文中的字符串仍然转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我发疯.我正在使用JAX-RS(Glassfish/Jersey)中的REST端点.我有一个方法应该接收一个字符串,存储它并返回它.整个端点应使用并产生JSON.但是每次我向该方法发布一个String时,它都会以转义的形式传递给我.例如.如果我发布:

This is driving me crazy. I'm working on a REST endpoint in JAX-RS (Glassfish / Jersey). I have a method that's supposed to receive a String, store it and return it. The entire endpoint should consume and produce JSON. But every time I post a String to the method, it's handed to me in escaped form. E.g. if I post:

fetch("http://localhost:8080/myapp/rest/myresource", {
  method: "post",
  credentials: 'same-origin',
  body: JSON.stringify("test\ntest"),
  headers: {
    "Content-Type": "application/json"
  }
})

,资源是:

@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MyResource {

    @POST
    public String set(@NotNull String value){
        // store it
        return storedValue;
    }
}

然后存储的内容返回给客户端,

then what is stored, and return to the client, is:

"test\ntest"

但是,如果我将String包裹在一个对象中:

If, however, I wrap the String in an object:

fetch("http://localhost:8080/myapp/rest/myresource", {
  method: "post",
  credentials: 'same-origin',
  body: JSON.stringify({value: "test\ntest"}),
  headers: {
    "Content-Type": "application/json"
  }
})

有资源

@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MyResource {

    @XmlRootElement
    public static class Wrapper {
        public String value;
    }

    @POST
    public String set(@NotNull Wrapper wrapper) {
        String value = wrapper.value;
        // store it
        return storedValue;
    }
}

然后存储并返回给客户端的值是

then the value that's stored and returned to the client is

test
test

我想念什么吗?

Glassfish 4.1.1
 - jersey 2.10.4-0
 - json 1.0-0.1

推荐答案

似乎是一个功能:传递字符串时,

It seems this is a feature: when passing Strings, Jackson assumes you're doing the encoding/decoding yourself.

我将把它留给后代.

这篇关于JAX-RS(泽西岛):JSON请求正文中的字符串仍然转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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