简体   繁体   中英

How to send a JsonObject in JerseyClient POST call?

I have a POJO class, in which one element is of type JSONObject :

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

I want to send it over a POST call using JerseyClient.

I tried this :

 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);

This fails with the error : No serializer found for class org.json.JSONObject

So then I added this :

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));

This does not fail, however in the request body which is actually being sent, has the data as an empty json.

Any idea how to make it work ?

The reason for keeping it a JsonObject is I will be getting this from one service and will pass it on to another without actually using it. So I don't want to model the internals of data .

You should add (de)serializators for JSONObject - jackson-datatype-json-org

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

And register module:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM