我用java制作了一个REST API,并且有以下DTO。
@ApiModel(value = "testType", description = "Test type")
public class TestType
{
private int type;
private String typeName;
private boolean isTypeSpecial;
private boolean isTypeTrue;
@JsonInclude(JsonInclude.Include.NON_ABSENT)
private List<typeMasterDTO> typeMasterList;
public TestType()
{
}
@ApiModelProperty(example = "0", value = "Type", required = true)
public int getType()
{
return type;
}
public void setType(int type)
{
this.type= type;
}
@ApiModelProperty(example = "Dragon", value = "Name of the typw", required = true)
public String getTypeName()
{
return typeName;
}
public void setTypeName(String typeName)
{
this.typeName= typeName;
}
@ApiModelProperty(value = "It is a special type", required = true)
public boolean isTypeSpecial()
{
return isTypeSpecial;
}
public void setTypeSpecial(boolean isTypeSpecial)
{
this.isTypeSpecial= isTypeSpecial;
}
@ApiModelProperty(value = "It is a true type", required = true)
public boolean isTypeTrue()
{
return isTypeTrue;
}
public void setTrueType(boolean isTypeTrue)
{
this.isTypeTrue= isTypeTrue;
}
@ApiModelProperty(value = "List of types")
public List<typeMasterDTO> getTypeMasterList()
{
return typeMasterList;
}
public void setTypeMasterList(List<typeMasterDTO> typeMasterList)
{
this.typeMasterList= typeMasterList;
}
}
在我的 API 类中,我从 sql 获取上述 DTO 的数据并使用以下代码返回响应:
Response com.mmp.rest.AbstractResource.buildResponse(Response<?> response, ResponseMode mode)
我得到的输出如下所示:
[
{
"type": 1,
"typeName": "New type",
"typeMasterList": [
{
"typeMaster": 0,
"typeMasterName": "Default"
},
{
"typeMaster": 1,
"typemasterName": "Custom"
}
],
"TypeTrue": false,
"TypeSpecial": true
}
]
所以我的疑问是:
- 为什么对象列表在响应中排在第三位,即使我已在 DTO 中将其声明为最后?
- 为什么 isTypeTrue 和 isTypeSpecial 在输出中显示为 TypeTrue 和 TypeSpecial?
- 为什么我先声明了 isTypeSpecial,但 isTypeTrue 先出现,isTypeSpecial 后来出现?
- 有什么方法可以了解 buildResponse 的工作原理吗?
最佳答案
- 因为顺序无关。在 JSON 级别上,它基本上是一个无序的键值映射。该顺序对于您或解析的人来说一定不重要。只有
[ ... ]
内的内容才会保持其顺序,因为这是一个有序列表/数组。 - boolean 字段的 getter 命名有点特殊,请参见例如For a boolean field, what is the naming convention for its getter/setter? -
is...
类似于常规 getter 的get...
,因此被剥离。 - 与 1 相同。
- 是的,例如设置断点并使用 IDE + 调试器单步执行该方法 - 但查看代码可能并不有趣
关于java - REST API 的 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52363590/