首页 > 解决方案 > 如何在 Spring Boot 中将 json 对象发送到 REST API

问题描述

我正在尝试将json对象发送到 API Post。

JSONParser jsonParser = new JSONParser();
    Object jsonArray = jsonParser.parse(new FileReader("mdpayload.json"));
    Invocation invocation;
    ClientBuilder clientBuilder = ClientBuilder.newBuilder()
            .hostnameVerifier((hostname, session) -> hostname.equalsIgnoreCase(session.getPeerHost()));
    Client client = clientBuilder.sslContext(getSSLContext()).build();
    WebTarget target = client.target(adhPutUrl);
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.setSerializationInclusion(Include.NON_NULL);
    String entityString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json9);
    //System.out.println(" Request for M2 :::\n" + json9);
    invocation = target.request().headers(getRequestHeaders())
            .build("POST", Entity.entity(json9, MediaType.APPLICATION_JSON))
            .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
    Response adhResponse = invocation.invoke();
    System.out.println("Response is "+adhResponse.getStatus());

但我收到以下错误:

org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class net.minidev.json.JSONObject, genericType=class net.minidev.json.JSONObject.

标签: jsonspring-boot

解决方案


从技术上讲,您的服务作为请求接收的 application/json 内容没有实现。

正文编写器是您需要在项目中拥有的一个实现,一个实现 JAX-RS 中定义的接口的类。

这是您可以添加的一个有用的库。

<dependency>
  <groupId>org.glassfish.jersey.media</groupId>
  <artifactId>jersey-media-json-jackson</artifactId>
  <scope>runtime</scope>
</dependency>

您可以使用一些解决方案和库,这取决于您使用的服务器。


推荐阅读