Getting data as a JSON object

I in my controller class a has the following method:

import javax.json.Json;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;


@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.TEXT_PLAIN})
@Path("/message")
public String postMessage(Json json,
    @Context HttpServletRequest request) {
   System.out.println("message");
   return "ok";
}

The problem is what I am posting POSTby doing curl:

curl -H "Content-Type: application/json" -X 
POST -d '{"key":"value"}' http://localhost:8080/message

I get HTTP Status 415 - Unsupported Media Typeas if I did not send JSON. When I change Json json,to String body, the controller is working fine.

In web.xmlI have:

<servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

EDIT

I had the wrong JSON as suggested in the comments. However, even with the correct one, for example, the {"key":"value"}code will not work.

+4
source share
3 answers

, jackson ObjectMapper . , , mapper , javax.json.Json, :

import javax.json.Json;
import com.fasterxml.jackson.databind.ObjectMapper;
// (...)
ObjectMapper mapper = new ObjectMapper();
Json json = mapper.readValue("{\"key\": \"value\"}", Json.class);

:

UnrecognizedPropertyException: Unrecognized field "key" (class javax.json.Json)

, POJO json-, :

class MyMessage {
  public String key; //for simplicity, you probably will use accessor methods
}

:

MyMessage msg = mapper.readValue("{\"key\": \"value\"}", MyMessage.class);

:

@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.TEXT_PLAIN})
@Path("/message")
public String postMessage(MyMessage msg) {
  System.out.println(msg.key);
  return "ok";
}
+1

. , ResourceConfig, register(JacksonFeature.class), :

public class ApplicationConfig extends ResourceConfig {

    public ApplicationConfig() {
        super(MyController.class);

        property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);
        register(JacksonFeature.class);
    }
}
+1

Make sure you have an implementation of MessageBodyReader in your class path that can consume JSON

0
source

Source: https://habr.com/ru/post/1695348/


All Articles