Reputation: 71
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.
Upvotes: 2
Views: 10705
Reputation: 21104
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.
Upvotes: 3
Reputation: 174
You can directly pass the List of your Object like this:
public Response definedSubGrupo(@QueryParam("Us") int US, List<YourObject> data)
Upvotes: 0