Create empty Json body for HttpEntity

Viewed 10908

So I can't figure out this seemingly simplest problem. I want to create HttpEntity where header has content-type application/json with body being an empty Json object:

{}

Right all I have available is Jackson, however no matter what I build (tried JsonNodeFactory.instance.nullNode() and ObjectNode with null object), it cant seem to create proper empty Json object. String "{}" or null doesn't work either. Any ideas?

Edit: guys...I'm sorry for wasting your time, turns out API I was calling was returning incorrect bad request response (400) for the wrong reasons. The request was actually correct. I'll just accept first correct answer

2 Answers

An easy way is to use the ObjectMapper to create an empty JSON ObjectNode and then serialize it:

ObjectMapper mapper = new ObjectMapper();
ObjectNode obj = mapper.createObjectNode();

String s = mapper.writeValueAsString(obj);  // yields "{}"

There is no need for mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

Maybe like this:

/**
 * Produce an empty HttpEntity
 */
public HttpEntity<String> getJsonEntityEmpty() {
    HttpEntity<String> entity = null;

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    String requestJson;
    requestJson = "{}";
    entity = new HttpEntity<String>(requestJson,headers);

    return entity;
}
Related