java - 将 Json 传递给 Rest 并通过 JSONObject 接收

标签 java json web-services rest jersey

我有以下服务器端代码:-

    import org.json.JSONObject;
    @Path("/user")
    public class Users {

    @POST
    @Path("register")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response registerUser(JSONObject userDetails) {
        return Response.status(Status.ACCEPTED).entity("User Created.Details are: " + userDetails).build();
    }
}

当我尝试使用以下代码调用它时,我收到了 415 错误。您能告诉我解决这个问题的方法吗?

{
    "user_id": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="315c50425950715c545442595a501f525e5c" rel="noreferrer noopener nofollow">[email protected]</a>",
    "password": "mashakawa",

    "user_profile": {
        "name": "Masha",
        "city": "New York",
        "email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cda0acacbea5ac8da6acbaace3aea2a0" rel="noreferrer noopener nofollow">[email protected]</a>",
        "age": 20
    },

    "user_settings": {
        "phone_number": "+91898342123"
    }
}

顺便说一句,我正在使用 Jersey 。

最佳答案

在 JAX-RS 中,您必须创建一个 JSON MessageBodyReader那将readFrom InputStream并返回 JSONObject .

@Provider
@Consumes(MediaType.APPLICATION_JSON)
public class JSONObjectMessageBodyReader implements MessageBodyReader<JSONObject> {

    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return true;
    }

    public JSONObject readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws java.io.IOException, javax.ws.rs.WebApplicationException {
        //Using entityStream, read the content and return a  JSONObject back...
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(entityStream, "UTF-8")); 
        StringBuilder responseStrBuilder = new StringBuilder();

        String inputStr;
        while ((inputStr = streamReader.readLine()) != null)
            responseStrBuilder.append(inputStr);

        return new JSONObject(responseStrBuilder.toString());
    }
}

关于java - 将 Json 传递给 Rest 并通过 JSONObject 接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33362957/

相关文章:

weblogic - 64 位 Weblogic 服务器上的 32 位 JDK

json - 处理 json 数据时出错 : The data couldn’t be read because it isn’t in the correct format

json - 如何合并 bash shell 中唯一的对象 TargetGroupARNs 和 TargetGroupArn?

java - Axis 1.4 服务上的授权 header

没有 IIS 的 c# rest webservice

Java 8 : Generic type inference improvements

java - 在 Eclipse 中导出 Java 项目时包含外部 jar

java - 为什么需要两个字符串或两个数组来完成此任务?

参数化查询中的 JavaScript 错误

java - 定义 SOAP java Web 服务中字段的预期值