Reputation: 313
In my response, I would like to add the size of the JSON to header, Here is what I tried and did not work (the response was empty):
return Response.ok(OBJECT_MAPPER.writeValueAsString(myObject), MediaType.APPLICATION_JSON).header(HttpHeaders.CONTENT_LENGTH), 20).build();
As you can see, I am hard coding the length, but it would be great if I could use the API to do it.
Solution
Well, byte size can be returned as below, depending on encoding. Below code would do it without implementing MessageBodyWriter
interface:
String str = OBJECT_MAPPER.writeValueAsString(myObject);
return Response.ok(str , MediaType.APPLICATION_JSON).header(HttpHeaders.CONTENT_LENGTH), str.getBytes("UTF-8").length)).build();
Upvotes: 3
Views: 3322
Reputation: 313
implementing MessageBodyWriter
interface:
String str = OBJECT_MAPPER.writeValueAsString(myObject);
return Response.ok(str , MediaType.APPLICATION_JSON).header(HttpHeaders.CONTENT_LENGTH), str.getBytes("UTF-8").length)).build();
Upvotes: 1