我正在尝试使用用 Entity.json
包装的普通旧 Java 对象来进行 POST 调用。我正在使用以下依赖项:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
这是我的 POST 函数的用法:
public String testPostCall(TestParams params) {
return target.request(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.post(Entity.json(params), String.class);
}
我认为问题出在 Entity.json(params)
中。我得到的错误是:
javax.ws.rs.ProcessingException:未找到类 TestParams 的消息正文编写器
。
这是我的 TestParams
类的样子:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class TestParams {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
将 POJO 类 TestParams
转换为 JSON 是否缺少依赖项?或者我使用了错误的注释?我想使用一个主要服务于 POST 调用的 API。任何帮助将不胜感激!
最佳答案
我想出了如何将 this link 中的 POJO 转换为 JSON然后使用以下代码:
public String testPostCall(TestParams params) {
try {
return target.request(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.post(Entity.json(mapper.writeValueAsString(params)), String.class);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
关于java - 使用 javaee-api 使用 POST API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60925968/