0

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. 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

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

JSON Object array output when having more objects:

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

1 Answer 1

1

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:

<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>. The way this implementation serializes lists is to always return a JSON array, even for the single argument list. 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?

Sign up to request clarification or add additional context in comments.

Comments

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.