简体   繁体   中英

JAX-RS REST service returning boolean as string

I am using JAX-RS to produce a RESTful service. However when requesting JSON, boolean values are returned as a quoted string {"boolValue":"true"} rather than a boolean value {"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

@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:

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. It works great. I've used Jettison in the past, but had lots of issues with it. You will probably have to configure your jax-rs provider to use jackson, since it doesn't look like it's already using it.

Another tip: no need for @XmlRootElement when using jackson, unless you also want to provide jax-b xml using the same beans.

In my case the JSON output was displaying all properties as Strings (including primitive data types). Adding this to my web.xml fixed the problem.

<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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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