0

I'm working with REST services using Jersey for my JSON handle. I'd like to make a method which consumes a generic object. Is there a way to deserialize it without a bean class?

JSON:

{
    "id": "2",
    "name": "John"  
}

Current method (using bean class):

@Path("/loginCheck")
    @POST
    @Consumes({ MediaType.APPLICATION_JSON })
    @Produces({ MediaType.APPLICATION_JSON })
    public Object checkLoginStatus(Object a) {
      // Check login status function
    }

I was reading about something with a HashMap which may work or maybe casting my Object with an inside class into the same method.

Any Ideas? Thanks.

escapesequence
  • 202
  • 4
  • 12
Juan BG
  • 87
  • 1
  • 2
  • 7
  • Besides my answer, I'd like to ask what are you trying to achieve by consuming different objects in one method? Probably there's some easier solution. – Aleksei Budiak Aug 22 '17 at 17:02
  • @AlekseiBudiak Your answer looks great, And works for these simple json, but I wanted skip the mapping with a bean when I have a nested json, something like do a temporal class only for deserialize but without create it. – Juan BG Aug 22 '17 at 17:12
  • That solution should work with any JSON object (including the one with nested objects). There's alternative to what I've suggested - [MessageBodyReaders](https://jersey.github.io/documentation/latest/message-body-workers.html#d0e6838). You can use them to add custom deserialization logic to Jersey. Unfortunately, there's no easy way to have some kind of temporal class specific to the request. – Aleksei Budiak Aug 22 '17 at 17:28
  • @Jarrod Roberson this is not a duplicate of any of the linked questions. Please read carefully. – Aleksei Budiak Aug 24 '17 at 21:01

2 Answers2

0

You can achieve consuming anything by a single method by specifying String parameter type.

@Path("/loginCheck")
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Object checkLoginStatus(String pureJsonString) {
}

The Map representation is available only for application/x-www-form-urlencoded MIME type, so it's not your case if you want to consume JSON. You can read more about this topic in Jersey docs.

Aleksei Budiak
  • 871
  • 5
  • 16
0

Based in Aleksei answer, I found a solution I post it hoping that it helps to someone:

            @Path("/loginCheck")
            @POST
            @Consumes({ MediaType.APPLICATION_JSON })
            @Produces({ MediaType.APPLICATION_JSON })
            public Object checkLoginStatus(String a) {
                JSONObject jsonAnswer = new JSONObject();
                ObjectMapper mapper = new ObjectMapper();
                try {
                    JsonNode rootNode = mapper.readTree(a);
                    System.out.println(rootNode.get("id").getIntValue());

                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
Juan BG
  • 87
  • 1
  • 2
  • 7