我有以下服务器端代码: -
item[@"Month"]
一旦我尝试使用以下内容调用此选项,我收到415错误。能告诉我解决这个问题的方法吗?
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();
}
}
顺便说一句,我正在使用泽西岛。
答案 0 :(得分:2)
在JAX-RS中,您必须创建一个MessageBodyReader
readFrom
并返回InputStream
的JSON 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());
}
}
答案 1 :(得分:0)
一种简单的方法是 -
public void parseJson(WebResource service) throws UniformInterfaceException, JSONException {
JSONArray resultArray = new JSONArray(service.path("resources/test/json/Tom").get(String.class));
List<User> userList = new ArrayList<User>();
for (int count = 0; count < resultArray.length(); count++) {
JSONObject userObject = resultArray.getJSONObject(count);
// this is tor read a sample JSON., this code will change according to your need.
User user = new User(userObject.get("name").toString(), userObject.get("surname").toString(), userObject.get("address").toString());
userList.add(user);
}
System.out.println(userList);
}
此代码专门针对Jersey Web服务编写。
请在泽西岛找到更多编码链接 -
Creating Webservices with Maven and Jersy
编辑:(客户端需要在其类路径中使用java-json.jar来开发此代码)。