如何在 RESTFUL Web 服务中将 POST 请求从 XML 转换为 JSON


@POST    
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String createUser(@FormParam("id") int id,
@FormParam("name") String name,
@FormParam("profession") String profession,
@Context HttpServletResponse servletResponse) throws IOException{
User user = new User(id, name, profession);
int result = userDao.addUser(user);
if(result == 1){
return SUCCESS_RESULT;
}
return FAILURE_RESULT;
}

强文本

参考 : https://www.tutorialspoint.com/restful/restful_methods.htm

生成和使用共享内容类型和接受标头。 您可以继续获取输入作为应用程序/Json。 但是我会给你XML到JSON的转换 使用 jaxb 加载 XML

Catalog catalog = JAXB.unmarshal(new File(xmlFile), Catalog.class);

现在你必须序列化 java 对象

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(System.out, catalog);

大功告成。!

如果要以 JSON 形式返回值,请删除 @Produces(MediaType.APPLICATION_XML( 并使用@Produces(MediaType.APPLICATION_JSON( 而不是 XML。默认媒体类型始终为 JSON 但是在您的代码中,您返回的是一个根本不是 JSON 的 STRING 值。如果您坚持返回字符串值,请使用 @Produces(MediaType.APPLICATION_JSON_VALUE( 它将返回相当于 MediaType.APPLICATION_JSON 的字符串。

使用

@Produces(MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON) 
at method level

和使用

@XMLRootElement

在波乔类级别

最新更新