使用 Jackson 的 ObjectMapper 的 JSON 对象顺序

新手上路,请多包涵

我正在使用 ObjectMapper 进行 java-json 映射。

 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 声明中的顺序相同。有没有办法指定它?也许带有注释或类似的东西?

原文由 justSaid 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 679
2 个回答
@JsonPropertyOrder({ "id", "label", "target", "source", "attributes" })
public class Relation { ... }

原文由 Andrey Atapin 发布,翻译遵循 CC BY-SA 3.0 许可协议

你知道有一种方便的方法来指定字母顺序吗?

 @JsonPropertyOrder(alphabetic = true)
public class Relation { ... }

如果您有特定要求,请在此处配置自定义排序:

 @JsonPropertyOrder({ "id", "label", "target", "source", "attributes" })
public class Relation { ... }

原文由 naXa stands with Ukraine 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题