我有以下服务器端代码:-
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/