简体   繁体   English

REST Web服务未返回JSON数组

[英]Rest web service not returning an JSON array

In the web service call, if the response is a list containing a single element, the REST web service returns a JSON object instead of a JSON array. 在Web服务调用中,如果响应是包含单个元素的列表,则REST Web服务将返回JSON对象而不是JSON数组。 How can I always return an array? 我如何总是返回一个数组?

@GET
@Produces("application/json")
@Path("/chekinList")
public List<LocationReguest> getChekinList(@FormParam("childID") String userName,@FormParam("appkey") String appkey,@FormParam("appPassword") String appPassword) // Getting the list of check in list
{

    LocationController locationController = new LocationController(); //Controller object
    List<LocationReguest> locreqlist = locationController.getChekinList(userName);   //Calling controller function
    return locreqlist;   //return proper representation object
}

Example : 范例

JSON Object output when having one object 具有一个对象时的JSON对象输出

{"childRequest":{"childName":"test123Child","childUserName":"add"}}

JSON Object array output when having more objects: 具有更多对象时的JSON对象数组输出:

{"childRequest":[{"childName":"Child ONE","childUserName":"chlid1"},{"childName":"abayakoon","childUserName":"abey"}]}

You need to write a custom implementation of MessageBodyWriter, but instead of reinventing the wheel perhaps it's easier to just use a dependency containing it: 您需要编写MessageBodyWriter的自定义实现,但与其重新发明轮子,不如直接使用包含它的依赖项可能会更容易:

<dependency>
  <groupId>com.fasterxml.jackson.jaxrs</groupId>
  <artifactId>jackson-jaxrs-json-provider</artifactId>
  <version>2.4.2</version>
</dependency>

It adds a provider to the classpath used by JAX-RS to serialize the return value of a REST call to JSON, in your case List<LocationReguest> . 它将提供程序添加到JAX-RS所使用的类路径中,以序列化对JSON的REST调用的返回值(在您的情况下为List<LocationReguest> The way this implementation serializes lists is to always return a JSON array, even for the single argument list. 此实现序列化列表的方式是始终返回JSON数组,即使对于单个参数列表也是如此。 Just how you want it. 就是您想要的。

At the moment it's likely that your app already has a provider that knows how to serialize lists, so what dependencies are you currently using? 目前,您的应用可能已经有一个知道如何序列化列表的提供程序,那么您当前正在使用哪些依赖项?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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