2016-04-02 5 views
1

プロジェクトは、2つのエンティティがあります:Gsonやジャクソンを使用してJSONへJSONにエンティティを休止状態に変換:全体ではなく、オブジェクトのoblectId

@Entity 
public class Customer { 
@Id 
@GeneratedValue(strategy = IDENTITY) 
@Column(name = "id", unique = true, nullable = false) 
private Integer id; 

@ManyToOne(fetch = FetchType.LAZY) 
@JoinColumn(name = "city_id", nullable = true) 
private City city; 
... 
} 

@Entity 
public class City { 
@Id 
@GeneratedValue(strategy = IDENTITY) 
@Column(name = "id", unique = true, nullable = false) 
private Integer id; 

@Column(name = "name", nullable = false) 
private String name; 
... 
} 

Cutomerエンティティは

{ 
"id":1, 
"city":{"id":1, "name":"New York"} 
} 

として変換し、

私はそれが変換されたいので

{ 
"id":1, 
"city_id":1 
} 

私はgsonやjacksonからどうすればいいですか?

+0

これを実現するには、カスタムシリアライザを使用する必要があります。 @Satmurat –

+1

このリンクで自分の回答を確認してください> [シリアライザのカスタマイズ方法](https://stackoverflow.com/questions/35592831/should-serialization-logic-be-in-the-entity-or-other-class/35593831#35593831) –

+1

@VikrantKashyap、各エンティティのシリアライザの作成がうまくいかない。 – Satmurat

答えて

0

この質問はあなたに役立つかもしれません。

Gson: How to exclude specific fields from Serialization without annotations

これを実現するための直接的な方法があるかどうかはわからないが、それを行うことが可能な間接的な方法があります。たとえば、private City citytransientとすると、単純に都市IDとなるcity_idという別のフィールドが公開される可能性があります。これは次のようになります。

@Entity 
public class Customer { 
    @Id 
    @GeneratedValue(strategy = IDENTITY) 
    @Column(name = "id", unique = true, nullable = false) 
    private Integer id; 

    @ManyToOne(fetch = FetchType.LAZY) 
    @JoinColumn(name = "city_id", nullable = true) 
    private transient City city; 

    private int city_id; 
    ... 
}