1

Project has two entities:

@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;
...
}

and

@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 entity to JSON using Gson or Jackson converts as

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

I want it is converts as

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

How I can do that via gson or jackson?

Satmurat
  • 41
  • 7

1 Answers1

0

This question might be helpful to you.

Gson: How to exclude specific fields from Serialization without annotations

I don't know if there is a direct way to accomplish this, but there are indirect ways in which it can be done. For instance, you could mark private City city as transient, and then you could expose another field called city_id that would simply be the city id. It would look something like this:

@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;
    ...
}
Community
  • 1
  • 1
Alex Parker
  • 1,533
  • 3
  • 16
  • 38