2

Model

public class Organisation {

    private String name;

    public Organisation() { }

    public Organisation(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

controller

    @RequestMapping(method = RequestMethod.GET)
    public List<Organisation> getAll() {
        Organisation organisation = new Organisation("google");
        List<Organisation> organisations = new ArrayList<>();
        organisations.add(organisation);
        return organisations;
    }

This will give out response like this:

[
  {
    "name": "google"
  }
]

What if we want something like this:

{
  "data": [{
    "type": "organisations"
    "attributes": {
      "name": "google"
    }
  ]
}

So how to customize the json. I know that Spring MVC by default uses Jackson to convert models into JSON. Is there a way to customize it. I am trying to send response in JSONApi standard. Also can someone tell how to create links in responses

1 Answer 1

2

Create Classes as:

public class Object1 {
   private List<Object2> data;

   public Object1() {
   }

   public Object1(List<Object2> data) {
      this.data = data;
   }
   //getters and setters
}

public class Object2 {

   private String type;
   private Object3 attributes;

   public Object2() {
   }

   public Object2(String type, Object3 attributes) {
      this.type = type;
      this.attributes = attributes;
   }
    //getters and setters
}

public class Object3 {
   private String name;

   public Object3(String name) {
      this.name = name;
   }

   public Object3() {
   }

    //getters and setters
}

Now your controller method shoul be like:

@RequestMapping(method = RequestMethod.GET)
    public Object3 getAll() {
        List<Object2> data = new ArrayList<>();
        data.add(new Object2("organisations", new Object3("google")));

        return new Object1(data);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.