2013-10-09 45 views
51

私はObjectMapperを使用してjava-jsonマッピングを行っています。ジャクソンのObjectMapperを使用した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宣言と同じ順序で欲しいです。それを指定する方法はありますか?おそらくアノテーションやそのようなものがあるでしょうか?

+2

コード/デザインの匂いに重大な意味を持つプロパティの順序。 JSONを消費しているものであれば、その注文に気を付けるべきではありません(リストにはい、プロパティーはありません)。 – ach

+9

私は読みやすさのためにそれを必要としています:-) – justSaid

+1

@achそれはちょうど真実ではありません。順序付けられたマップは非常に一般的で、非常に有用なデータ型です。欲望の秩序は全くのにおいではありません。 – goat

答えて

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

@justSaid、どういう意味ですか?リスト要素のフィールドを同じ方法でソートしますか? –

1

あなたは@XmlAccessorType(XmlAccessType.FIELD)

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

@JsonPropertyOrderが追加される新しいjarファイルを必要と使用することができます。

+3

@JsonPropertyOrderは、すでに含まれているjacksonを使用しているため、新しいjarを必要としません。 – Patrick

+0

使用しているフレームワークによって異なります.Jsonを使用しないと、上記の実装と一緒にjsonとxmlの両方に適用され、xml形式のデータを返す場合は余分な設定が不要です。 –

+0

はい、問題はjacksonを使って尋ねられました。 jacksonを使わずにソリューションを提供したい場合は、あなたの答えをより明確にする必要があります。 – Patrick

関連する問題