Program Tip

Jackson의 ObjectMapper를 사용한 JSON 객체 순서

programtip 2020. 10. 18. 19:01
반응형

Jackson의 ObjectMapper를 사용한 JSON 객체 순서


ObjectMapper사용하여 Java-json 매핑을 수행하고 있습니다.

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
ow.writeValue(new File( fileName +".json"), jsonObj);

이것은 내 자바 클래스입니다.

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" : ""
    } ]

  }

내 자바 선언과 동일한 순서로 원합니다. 그것을 지정하는 방법이 있습니까? 주석이나 그와 같은 것들로?


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

당신이 사용할 수있는 @XmlAccessorType(XmlAccessType.FIELD)

@XmlType(name = "response", propOrder = { "prop1", "prop2",
        "prop3", "prop4", "prop5", "prop6" }).

@JsonPropertyOrder 추가하려면 새 항아리가 필요합니다.

참고 URL : https://stackoverflow.com/questions/19272830/order-of-json-objects-using-jacksons-objectmapper

반응형