2

I need some help with REST APIs. I'm trying to send JSON data through an API by using Postman's Body to test it. It appears to work, but when I check the Array by Debugging the code it says that the Array's size is 0.

I'm trying to send this:

{
   "data":[
      { 
         "name":"",
         "valor":"",
         "check":"0",
         "ind":"1"
      },
      {
         "name":"",
         "valor":"* FT NPR **",
         "check":"1",
         "ind":"0"
      }
    ]
}

I'm using Java EE. I've tried to parsing the code to String but I don't know if I'm doing it wrong or if it just doesn't work.

This is the code:

@GET
@Path("subGroup")
@Produces("application/json")
@Consumes(MediaType.APPLICATION_JSON)
public Response definedSubGrupo(@QueryParam("Us") int US, JSONArray data) 
{
   String Data=UtilClass.definedSubGrupo(data);
   return UtilClass.getReturn(Data);
}

I expected the full JSON that I sent, but the actual output is nothing (size=0).

Thank you.

2
  • This request here is not a JSONArray - it's a JSONObject that has JSONArray inside it, accessible by "data" property. Commented Apr 1, 2019 at 18:55
  • Updated with an example of how to retrieve the JSONArray. See answer. Commented Apr 1, 2019 at 19:05

2 Answers 2

3

You're on a JavaEE container, and, given the annotations you're specifying, you're building on top of JAX-RS. With JAX-RS you can accept a request body as a plain String

public Response definedSubGrupo(@QueryParam("Us")final int US, final String jsonBody) { ... }

You can then convert that jsonBody String to an object representing the JSON document structure using one of the available libraries in the market (JSON-java, Gson, Jackson, etc.).

For example, with Jackson, you'd have

final TreeNode treeNode = objectMapper.readTree(jsonBody);

With JSON-Java, you can have

final JSONObject jsonObject = new JSONObject(jsonBody);
final JSONArray data = jsonObject.getJSONArray("data");

As of now, what you're telling JAX-RS is basically "map the request body to this JSONArray class".
Unfortunately the class layout of JSONArray seems not compatible with the JSON you're sending, so JAX-RS simply create a new, "empty", instance.

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

Comments

0

You can directly pass the List of your Object like this:

public Response definedSubGrupo(@QueryParam("Us") int US, List<YourObject> data) 

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.