简体   繁体   中英

How to send JSONArray through a Rest API

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.

您可以像这样直接传递对象列表:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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