title: Encode Response in REST service
body: <p>I use class <code>javax.ws.rs.core.Response</code> in my service method:</p>
  
  <pre><code>@GET
  @Path("/object/{id}")    
  @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Response findObject(@Context HttpHeaders headers,
                                   @PathParam("id") String objectId) {
      Object object = getObject(objectId);
      return createResponse(object, headers);
  }
  
  private Response createResponse(Object object, HttpHeaders headers) {
      Response.ResponseBuilder responseBuilder = Response
              .ok()
              .entity(object)
              .type(MediaType.APPLICATION_JSON_TYPE)
              .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
              .build();
  }
  </code></pre>
  
  <p>And instance of <code>Response</code> contents hierarchy of my system which is contained in the instance <code>object</code>. This's object with all its children and their properties. And I want encoding values of properties in <code>object</code>. I need to give in response percent-encoding symbols instead of space in names for example. I need encoding whole my response including all fields. According to the UTF-8 encoding. For example, instead of value of some field <code>'His name: John'</code> I need have <code>'His20%name%3A20%John'</code> in my response. And similarly for all fields without exception in the whole hierarchy.</p>
  
  <p>I didn't find anything better than how each field was handled manually using the method <a href="https://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html" rel="nofollow noreferrer">URLEncoder.encode(String s, String enc)</a>:</p>
  
  <pre><code>fieldValue = URLEncoder.encode(fieldValue, "UTF-8");
  </code></pre>
  
  <p>But in this case I need to manually go through all the fields that are in all the objects of my hierarchy coming in response. Maybe there is a more standard and correct way to do this?</p>
  
  <p>And some fields are not string and have for example type BigDecimal. They can contain delimiters. How do I process them? Is there any way to encode the entire object response before return?</p>