如何在 JerseyClient POST 调用中发送 JsonObject?

How to send a JsonObject in JerseyClient POST call?

我有一个 POJO class,其中一个元素是 JSONObject 类型:

 public static class TestRequest {
    org.json.JSONObject data;
  }

我想使用 JerseyClient 通过 POST 调用发送它。

我试过这个:

 Client client = new Client();
    TestRequest request = new TestRequest();
    Map<Long, String> data = Maps.newHashMap();
    data.put(1L, "abc");

    JSONObject object = new JSONObject(data);
    request.setData(object);

    ClientResponse response = client.resource("http://localhost:18000/test/url")
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .type(MediaType.APPLICATION_JSON_TYPE)
            .post(ClientResponse.class, request);

失败并出现错误: 未找到 class org.json.JSONObject

的序列化程序

然后我添加了这个:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

client.resource("http://localhost:18000/test/url")
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .type(MediaType.APPLICATION_JSON_TYPE)
            .post(ClientResponse.class, mapper.writeValueAsBytes(request));

这不会失败,但是在实际发送的请求正文中,data 为空 json。

知道如何让它发挥作用吗?

将它保留为 JsonObject 的原因是我将从一项服务获取它并将其传递给另一项服务而不实际使用它。所以我不想对 data.

的内部建模

您应该为 JSONObject 添加(反)序列化器 - jackson-datatype-json-org

<dependency>
   <groupId>com.fasterxml.jackson.datatype</groupId>
   <artifactId>jackson-datatype-json-org</artifactId>
   <version>2.4.0</version>
</dependency>

并注册模块:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JsonOrgModule());