0

I currently have a webservice that returns this JSON:

[  
   {  
      "id":1,
      "description":"RGB LED module"
   },
   {  
      "id":4,
      "description":"Motion Sensor module"
   },
   {  
      "id":3,
      "description":"Camera module"
   },
   {  
      "id":2,
      "description":"Display module"
   }
]

However, I need it to be:

{  
   "modules":[  
      {  
         "id":1,
         "description":"RGB LED module"
      },
      {  
         "id":4,
         "description":"Motion Sensor module"
      },
      {  
         "id":3,
         "description":"Camera module"
      },
      {  
         "id":2,
         "description":"Display module"
      }
   ]
}

How can I achieve this?

This is my current Java code:

  @GET
  @Path("availableModules")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getModules()
  {        
     return Response.ok(createAvailableModuleList()) //200
        .header("Access-Control-Allow-Origin","*")
        .build();
  }

createAvailableModuleList returns a mocked ArrayList for now, and looks like this:

  public List<Module> createAvailableModuleList()
  {
    Module ledModule=new Module(1, "RGB LED module");
    Module motionSensorModule=new Module(4, "Motion Sensor module");
    Module cameraModule=new Module(3, "Camera module");
    Module displayModule=new Module(2, "Display module");

    List<Module> modules = new ArrayList<Module>();
    modules.add(ledModule);
    modules.add(motionSensorModule);
    modules.add(cameraModule);
    modules.add(displayModule);
    return modules;
  }
3
  • 1
    One way I can think of is to create class in which you assign Module list to. Commented Mar 23, 2016 at 20:46
  • How would that look like? A class with only the list of modules? And return the class in the response? Commented Mar 23, 2016 at 20:48
  • Yes, exactly how you described it. Commented Mar 23, 2016 at 20:49

1 Answer 1

2

Wrap the list in a map with one entry

 LinkedHashMap<String,Object> map = new LinkedHashMap<>();
 map.put("modules", createAvailableModuleList()); 
 return Response.ok(map)...
Sign up to request clarification or add additional context in comments.

2 Comments

this is even a better idea
Works like a charm! Thanks mate!

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.