简体   繁体   中英

Java Jersey JSON webservice proper array return

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

Wrap the list in a map with one entry

 LinkedHashMap<String,Object> map = new LinkedHashMap<>();
 map.put("modules", createAvailableModuleList()); 
 return Response.ok(map)...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM