0

How to send nested JSON input to Restful web service (using Java)?

eg. JSON input

{
  "item1": [
    {
      "name": "name1",
      "value": "value1",
      "subitems": [
        {
          "sname": "sname1",
          "svalue": "svalue1"
        },
        {
          "sname": "sname2",
          "svalue": "svalue2"
        }
      ],
      "attributes": [
        {
          "length": 25,
          "height": 25,
          "width": 30
        },
        {
          "length": 35,
          "height": 35,
          "width": 40
        }
      ]
    }
  ]
}
Termininja
  • 6,620
  • 12
  • 48
  • 49
Prit
  • 73
  • 1
  • 10

1 Answers1

0

You can create a class to map you json like this :

     public class item {
        private String name;
        private String value;
        private List<SubItem> subitems;
        private List<Attribute> attributes;
        // add here getters, setters and constructor
     }

     public class SubItem{
        private String name;
        private String svalue;
        //add here getters, setters and constructor
     }
     public class Attribute{
        private Integer length;
        private Integer height;
        private Integer width;
        //add here getters, setters and constructor
     }
  • Thanks! But how will we accept the Class in WebService Post method. – Prit Jun 16 '16 at 09:05
  • like this : @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public ReturnedView yourMethod(Item item) { ....} – maad el yadari Jun 16 '16 at 09:29
  • Thanks maad el yadari. So we can't use annotation like @Queryparam for such objects? – Prit Jun 16 '16 at 09:45
  • Getting following error: error occured in reading JSON : java.io.EOFException: No content to map to Object due to end of input at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2433) at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2366) at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1162) – Prit Jun 17 '16 at 06:45
  • Back end code was not expecting any Custom Object. Instead of passing Item object, I passed bodyObject and then mapping it with Item further using ObjectMapper. – Prit Jun 22 '16 at 06:36