如何 return 具有 @Produces(MediaType.APPLICATION_JSON) 的响应字符串?

How to return a string in response that have @Produces(MediaType.APPLICATION_JSON)?

@GET
@Path("/paises/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response findCuntryList(@PathParam("id")int id){
    try{
    ArrayList<Country> lista = new ArrayList<>();
    for(int i=0; i<10 ;i++){
        Country c = new Country();
        c.setId(i);
        c.setName("country"+i);
        c.setCode("countryIsoCode"+i);
        c.setRegion("region"+i);
        lista.add(c);
        }

    Country co = lista.stream().filter(x -> x.getId()==id).findAny().get();
    if(id > lista.size()-1) throw new Exception("That id is not correct");
    return Response.ok(co).build();
    }catch(Exception e){

        return Response.status(404).entity(e.getMessage()).build();
        }
    }

我想要return一个json当我没有异常但是当我有它时我需要return一个带有异常消息的字符串但是这个丢弃错误json 解析。

单引号字符串是有效的 JSON。所以你可以使用:

return Response.status(404).entity("\"" + e.getMessage() + "\"").build();

不过,我建议您改为 return JSON 对象。它使您可以灵活地 return 关于错误的额外元数据。

您可以使用 Map<String, Object>:

Map<String, Object> errorDetails = new HashMap<>();
errorDetails.put("message", e.getMessage());
return Response.status(404).entity(errorDetails).build();

或者为错误详情创建一个class:

public class ErrorDetails {

    private String message;

    ...
}
ErrorDetails errorDetails = new ErrorDetails;
errorDetails.setMessage(e.getMessage());
return Response.status(404).entity(errorDetails).build();

要报告 HTTP API 中的问题,请查看 RFC 7807

为什么您对使用 WILDCARD 表达式不感兴趣,

 @Path("getSupportEmail/{broadcastMprId}")
    @GET
    @Produces(MediaType.MEDIA_TYPE_WILDCARD)
    public Response getSupportEmailByBroadcastMprId(@PathParam("broadcastMprId") Integer broadcastMprId) {
        return Response.ok(broadcastMprBean.getSupportEmailByBroadcastMprId(broadcastMprId)).build();
    }

根据您提供的示例代码和该问题的标签,您最好使用异常处理程序,而不是捕获和 return 手工制作的消息,然后让您的 @GET 方法 return 你的域对象。 JAX-RS 库(在本例中为 Jersey?)会将其序列化为 JSON,因为您的方法使用 APPLICATION_JSON.

注释

https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-en/cn/part1/chapter7/exception_handling.html

特别针对泽西岛:https://howtodoinjava.com/jersey/jax-rs-jersey-custom-exceptions-handling-with-exceptionmapper/