REST API响应为json

时间:2017-09-26 09:22:48

标签: java json rest api objectmapper

我正在编写一个发送一些数据的REST API。我希望这些数据采用JSON格式。 我有这个Object Mapper(seprate类):

public PSSMonitorJacksonJsonProvider() {
    ObjectMapper objectMapper = locateMapper(ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE);

    // our custom date/time format
    objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z"));

    // omit null values
    objectMapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);

    objectMapper.setVisibility(JsonMethod.ALL, JsonAutoDetect.Visibility.ANY);

    // ignore unknown properties
    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}

和这个REST API:

@GET
@AnonymousAllowed
@Produces({MediaType.APPLICATION_JSON})
public Response getMessage() {
    return Response.ok(new ProjectResourceModel("Hell World", ""))
            .header("Access-Control-Allow-Headers", "Authorization, *")
            //.header("Access-Control-Allow-Origin", "http://localhost:4200")
            .header("Access-Control-Allow-Methods", "OPTIONS, GET")
            .header("Access-Control-Allow-Credentials", "*")
            .build();
}

/**
 * Returns the number of all projects
 * from bitbucket
 *
 * @return number of projects in bitbucket
 */
@GET
@Produces({MediaType.APPLICATION_JSON})
@Path("/number")
@AnonymousAllowed
public Response getNumberOfProjects() {

    return Response.ok((service.getNumberOfProjects()/*returns int*/))
            .header("Access-Control-Allow-Headers", "Authorization, *")
            .header("Access-Control-Allow-Origin", "http://localhost:4200")
            .header("Access-Control-Allow-Methods", "OPTIONS, GET")
            .header("Access-Control-Allow-Credentials", "*")
            .build();//gets the number of projects from the bitbucket api
}

只要我从模型返回一个对象然后我就可以完美地工作了,但是当我想直接返回一个int时它就不起作用了。它将它作为一个简单的int返回。我需要做什么,我的REST API返回/将其转换为json。我想全局映射所有响应,所以我不必自己映射每个响应。感谢

0 个答案:

没有答案