Java Jersey JSON Web服务正确的数组返回

标签 java json web-services rest

我目前有一个返回此 JSON 的 Web 服务:

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

但是,我需要它是:

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

我怎样才能实现这个目标?

这是我当前的 Java 代码:

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

createAvailableModuleList 现在返回一个模拟的 ArrayList,如下所示:

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

最佳答案

用一个条目将列表包装在 map 中

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

关于Java Jersey JSON Web服务正确的数组返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36188263/

相关文章:

java - 如何从android中的 ListView 中获取整数值?

java - 使用 EasyMock 测试参数值

javascript - 如何在不知道 javascript 中使用 JSON 的特定键的情况下获取属性值

java - JAX-WS 中的 HTTP 连接重用

web-services - 如何在Spring Boot中使用Tuckey urlrewrite访问使用?wsdl的服务

java - Hibernate 和 Oracle 夸大序列递增

java - 使用前后空格从短语中提取单词?

json - 无法让 Json 在 ag Grid 中显示只是说正在加载

java - 从 xml 响应中获取对象

java - 没有名为 'springSecurityFilterChain' 的 bean 被定义为 spring restful web 服务身份验证的异常