Pass a List as parameter in Restful Java web services

Asked

Viewed 1,348 times

2

Could someone explain to me how to receive a List as a parameter in a Restful Java webservices ? I’ve searched a lot of places, but I still can’t figure it out. Thank you in advance ! The code below is an example and as I did in my actual code. In the request, I send a JSON with the products, the web-services returns 200 OK, but print "[]".

@path("/incluirProdutos")
@consumes(MediaType.APPLICATION_JSON)
@produces(MediaType.APPLICATION_JSON)
public String incluirProdutos(List<Produto> produtos){ 

      return produtos.toString();
 }
  • Good morning, Just like there in the code. I don’t know if this is possible. It would be ?

  • I intend to make the server and the client, so I’ll do everything in Java. However, I could talk a little more about what would be the applicability of the serialization of the object, in this context ?

1 answer

0


The resolution for this is to use a class for the "wrap" of your list, follow an example below to help you:

// Wrapper
class Produtos {
  List<Produto> produtos
}

// JAX-RS
@path("/incluirProdutos")
@consumes(MediaType.APPLICATION_JSON)
@produces(MediaType.APPLICATION_JSON)
public String incluirProdutos(Produtos produtos){ 

      return produtos.toString();
}

// JSON
{
  "produtos": [
    {
      "nome": "teste"
    }
  ]
}
  • Leonardo, Java does not have such a native resource ? It is always necessary to resort to this solution ?

  • Usually that’s what’s being used, maybe in newer versions that will change. If the answer helped you don’t forget to mark it as useful and accept.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.