我使用 ObjectMapper 来做我的java-jsonMap。
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
ow.writeValue(new File( fileName +".json"), jsonObj);
字符串
这是我的Java类:
public class Relation {
private String id;
private String source;
private String target;
private String label;
private List<RelAttribute> attributes;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public void setAttributes(List<RelAttribute> attributes) {
this.attributes = attributes;
}
public List<RelAttribute> getAttributes() {
return attributes;
}
}
型
这就是我得到的
{
"id" : "-75da69d3-79c8-4000-a3d8-b10350a57a7e",
"attributes" : [ {
"attrName" : "ID",
"attrValue" : ""
}, {
"attrName" : "Description",
"attrValue" : "Primary Actor"
}, {
"attrName" : "Status",
"attrValue" : ""
} ],
"label" : "new Label",
"target" : "-46b238ac-b8b3-4230-b32c-be9707f8b691",
"source" : "-daa34638-061a-45e0-9f2e-35afd6c271e0"
}
型
所以我现在的问题是,我如何得到这个json输出:
{
"id" : "-75da69d3-79c8-4000-a3d8-b10350a57a7e",
"label" : "new Label",
"target" : "-46b238ac-b8b3-4230-b32c-be9707f8b691",
"source" : "-daa34638-061a-45e0-9f2e-35afd6c271e0",
"attributes" : [ {
"attrName" : "ID",
"attrValue" : ""
}, {
"attrName" : "Description",
"attrValue" : "Primary Actor"
}, {
"attrName" : "Status",
"attrValue" : ""
} ]
}
型
我希望它的顺序和我的java声明中的顺序一样。有没有办法指定它?也许用注解之类的东西?
7条答案
按热度按时间bq9c1y661#
字符串
nle07wnf2#
你知道有一种方便的方法来指定字母顺序吗?
字符串
如果您有特定的要求,这里您如何配置自定义排序:
型
rqqzpn5f3#
在生成的.class中字段的顺序是不确定的,所以你不能指望它。
如果你想要每个类的特定顺序,那么你需要使用其他答案中指定的方法之一。
如果你希望所有东西都默认为字母顺序(例如,为了保持JSON结构的一致性),那么你可以像这样配置ObjectMapper:
字符串
为了更一致的JSON,还可以考虑添加:
型
这种方法的一个优点是,您不必修改正在序列化的每个类。
e37o9pze4#
我今天发现了第三种方法,以防字母不是你想要的排序顺序。事实证明,在字段上添加@JsonProperty注解会在写作时将其放在最后。我发现,当我想指定一个不符合java命名约定的属性名时。
通过添加一个index属性,你可以定义顺序。最小的index放在第一位。
字符串
将呈现:
型
hivapdat5#
可以使用
@XmlAccessorType(XmlAccessType.FIELD)
字符串
@JsonPropertyOrder
需要添加新的jar。gdrx4gfi6#
根据this documentation,您可以全局配置Jackson 2 ObjectMapperBuilder。此类在spring-web依赖项中可用。
字符串
此外,您还可以使用@JsonProperty(index)来确定继承类中的顺序。
型
gzszwxb47#
我知道这可能有点晚了,但是如果你有一个有大量字段的对象,你的@JsonPropertyOrder会看起来很糟糕。你可以在你的对象中的每个字段上使用注解@JsonProperty(“nameOfField”),你的序列将被正确构建。像这样:
字符串
看看最后一个字段,我可能不会添加注解,因为字段的名称和结果json键的名称是匹配的。但在这种情况下,字段countries将位于json的第一位。