【问题标题】:string JSON without "" on JAXRS responseJAXRS 响应中不带“”的字符串 JSON
【发布时间】:2016-12-28 10:32:37
【问题描述】:

我已经创建了一个端点:

@Path(value = "/users")
@Produces(MediaType.APPLICATION_JSON)
public interface IUserCommtyEndpoint {
    @POST
    public abstract Response create(
        @HeaderParam("user") String username
    );

如您所见,我已指定此端点生成 MetiaType.APPLICATION_JSON

这是实现:

@Override
public Response create(String username) {
    String userId = "some string";
    return Response
        .created(this.uriInfo.getAbsolutePathBuilder().path(userId).build())
        .entity(userId)
        .build();
}

尽管如此,响应正文内容是some string,但没有""。因此,浏览器无法使用 json 格式解析此字符串值。

有什么想法吗?

【问题讨论】:

    标签: jakarta-ee jax-rs


    【解决方案1】:

    Here你可以找到答案。

    简而言之,发送单个字符串是不正确的。

    【讨论】:

    【解决方案2】:

    正如this answer 对“"" 是一个有效的 JSON 字符串吗?”问题所指出的,最新的 JSON RFC 7159 表明 "some string" 实际上是有效的 JSON。

    另一个answer帮助我找到了使用jackson解决问题服务器端的方法:

    import java.io.IOException;
    import java.io.OutputStream;
    import java.lang.annotation.Annotation;
    import java.lang.reflect.Type;
    import javax.ws.rs.WebApplicationException;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.MultivaluedMap;
    import javax.ws.rs.ext.MessageBodyWriter;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class StringMessageBodyWriter implements MessageBodyWriter<String> {
    
        @Override
        public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
            return type == String.class && MediaType.APPLICATION_JSON_TYPE.equals(mediaType);
        }
    
        @Override
        public void writeTo(final String t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream out) throws IOException, WebApplicationException {
            final ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(out, t);
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 2018-03-30
      相关资源
      最近更新 更多