简体   繁体   English

JAX-RS REST服务以字符串形式返回布尔值

[英]JAX-RS REST service returning boolean as string

I am using JAX-RS to produce a RESTful service. 我正在使用JAX-RS来生成RESTful服务。 However when requesting JSON, boolean values are returned as a quoted string {"boolValue":"true"} rather than a boolean value {"boolValue":true} . 但是,当请求JSON时,布尔值将作为带引号的字符串{"boolValue":"true"}而不是布尔值{"boolValue":true}

A simple object 一个简单的对象

@XmlRootElement
    public class JaxBoolTest {
    private boolean working;

    public boolean isWorking() {
        return working;
    }

    public void setWorking(boolean working) {
        this.working = working;
    }

}

A simple JAX-RS REST service 一个简单的JAX-RS REST服务

@Path("/jaxBoolTest")
public class JaxBoolTestResouce {
    @GET
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public JaxBoolTest getJaxBoolTest() {
        JaxBoolTest jbt = new JaxBoolTest();
        jbt.setWorking(false);
        return jbt;
    }
}

And the result: 结果:

{"working":"false"}

How do I get the boolean values as boolean values rather than strings? 如何获取布尔值而不是字符串的布尔值?

Using jaxson ( http://jackson.codehaus.org/ ) to serialize this worked out of the box: 使用jaxson( http://jackson.codehaus.org/ )进行序列化可以立即使用:

public class BooleanTest {
    @Test
    public void test() throws Exception{
        System.out.println(new ObjectMapper().writeValueAsString(new JaxBoolTest()));
    }
}

Produced this output: 产生此输出:

{"working":false}

I highly recommend using Jackson for serializing JSON. 我强烈建议使用Jackson来序列化JSON。 It works great. 效果很好。 I've used Jettison in the past, but had lots of issues with it. 我过去曾经使用过Jettison,但是有很多问题。 You will probably have to configure your jax-rs provider to use jackson, since it doesn't look like it's already using it. 您可能必须将jax-rs提供程序配置为使用jackson,因为它看起来好像已经在使用它。

Another tip: no need for @XmlRootElement when using jackson, unless you also want to provide jax-b xml using the same beans. 另一个提示:使用jackson时不需要@XmlRootElement,除非您还希望使用相同的bean提供jax-b xml。

In my case the JSON output was displaying all properties as Strings (including primitive data types). 在我的情况下,JSON输出将所有属性显示为字符串(包括原始数据类型)。 Adding this to my web.xml fixed the problem. 将此添加到我的web.xml中可以解决此问题。

<init-param>
  <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
  <param-value>true</param-value>
</init-param>
@POST @Path("/users")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Object controlUserExisting(Object requestEntity) {
    boolean result=RootBsn.controlUserExisting(requestEntity);

    JSONObject json=new JSONObject();
    json.put("result",result);

    return json.toString();
}

retrieving user existing Sended and returned{"result":true} (if exist) 检索用户现有的已发送和返回{“ result”:true}(如果存在)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM