使用swagger编辑器,我创建了一个post调用来使用一个json对象,我想简单地将其加载到数据库中,但是当我运行调用时,我得到了一个空的json对象。
这是我的json帖子的参数部分
"parameters": [
{
"in": "body",
"name": "body",
"description": "Add question to collection",
"required": true,
"schema": { "type" : "object", "additionalProperties" : {}
}
}
],
然后它创建一个"Body"模型,但我无法看到作为帖子一部分的 json:
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2016-01-22T20:49:03.229Z")
public class Body {
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Body body = (Body) o;
return true;
}
@Override
public int hashCode() {
return Objects.hash();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Body {n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("n", "n ");
}
}
如果我从消费中删除文本/json 并再次生成我的代码,我仍然看到身体模型存在问题并且能够拉入 json。 如果您查看 toString 方法,它会显示硬编码值,所以我看不出如何使用仅接受正文和安全上下文的 post 方法从帖子中提取 json。
当使用这个招摇的片段时,我对 http 接受有点困惑:
"post": {
"tags": [
"AskGrey"
],
"summary": "Create new askgrey.com question",
"operationId": "postAskGrey",
"consumes": [
"application/json",
"text/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "Add question to collection",
"required": true,
"schema": { "type" : "object", "additionalProperties" : {}
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "object"
}
}
},
"deprecated": false
}
生成的方法如下:
@Override
@POST
@Consumes("application/json")
public Response postAskGrey(Body body,SecurityContext securityContext)
throws NotFoundException {
因此,基于所有这些,我不确定如何提取帖子正文信息,通常我会从 http 请求中获取我需要的东西,但我似乎无法弄清楚如何使用它。
在发送数据之前HTTP ACCEPT
您应该检查您在发送数据时大摇大摆地设置的方法。
应该有几个接受方法,它们在将数据发送到服务器时的行为彼此不同。
因此,对于application/JSON
:数据是身体的一部分。
form-data
和x-www-form-urlencoded
:数据是标头的一部分。
经验来提供正确的代码来获取相关的 jSON 对象,但如何在 Java 中将 HTTP 请求正文转换为 JSON 对象,这个答案可能会有所帮助。
请查看以下 RFC 以获取更多信息
form-data
相关的 RFC https://www.rfc-editor.org/rfc/rfc7578
x-www-form-urlencoded
相关的 RFC https://datatracker.ietf.org/doc/html/draft-hoehrmann-urlencoded-01
application/JSON
相关的RFC https://www.ietf.org/rfc/rfc4627.txt
更新
相关 curl 命令:我从 swagger 现场演示中获取命令 http://petstore.swagger.io/#/pet 将您的json
粘贴到它并更改url, secret key
试一试!
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{
"id": 0,
"category": {
"id": 0,
"name": "string"
},
"name": "doggie",
"photoUrls": [
"string"
],
"tags": [
{
"id": 0,
"name": "string"
}
],
"status": "available"
}' 'http://petstore.swagger.io/v2/pet?api_key=special-key'