0

Fairly new Spring Developer here..

I've been using Spring for the last couple of days and managed to create a simple CRUD API using JPA and Spring Rest. Now, I want to have the flexibility of changing how the returned JSON is composed.

For example, I've got the following simple entity:

Table Name: Category

 - category_id
 - category_name

A GET request is returning the following JSON:

{
    categoryName: "Category 1",
    _links: {
        self: {
            href: "http://localhost:8080/faqsCategories/1"
        },
        faqsCategory: {
            href: "http://localhost:8080/faqsCategories/1"
        },
        faqsContent: {
            href: "http://localhost:8080/faqsCategories/1/faqsContent"
        }
    }
}

Now I want to remove the _links part and add additional content..

Is this possible in Spring?


Classes:

FaqsCategory (Entity)

@Entity
@Table(name = "faqs_category")
public class FaqsCategory {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long categoryId;

  private String categoryName;

  @OneToMany(targetEntity = FaqsContent.class, mappedBy = "faqsCategory")
  private Set<FaqsContent> faqsContent = new HashSet<>();

  protected FaqsCategory() {
  }
  .....
}

FaqsCategoryRepository

@RepositoryRestResource
public interface FaqsCategoryRepository extends JpaRepository<FaqsCategory, Long> {

}
a better oliver
  • 26,330
  • 2
  • 58
  • 66
cgval
  • 1,096
  • 5
  • 14
  • 31
  • Kindly share restcontroller code along with the service and dao – Mudassar Jun 22 '16 at 12:53
  • @Mudassar, I don't have any rest controllers.. Just added the service and JPA Repository code.. – cgval Jun 22 '16 at 12:55
  • You could check [this answered question](http://stackoverflow.com/questions/25020331/spring-mvc-how-to-modify-json-response-sent-from-controller/25155407) – Alexander Jun 22 '16 at 13:31

1 Answers1

0

the solution is to use @JsonProperty("...") which in your case should look like

@JsonProperty("links")
@OneToMany(targetEntity = FaqsContent.class, mappedBy = "faqsCategory")
private Set<FaqsContent> faqsContent = new HashSet<>();

"links" will be the name appearing instead of "_links" there in your json response

Mudassar
  • 3,135
  • 17
  • 22