ContentUtils { public static String serializeContent(Object content, String mediaType) { if (content == null) { return null; } if (content instanceof String) { return (String) content; } if (mediaType == null) { return content.toString(); } String result = null; String mediaTypeLowerCase = mediaType.toLowerCase(); try { if (mediaTypeLowerCase.endsWith("json")) { result = Json.mapper().writeValueAsString(content); } else if (mediaTypeLowerCase.endsWith("yaml")) { result = Yaml.mapper().writeValueAsString(content); } else if (mediaTypeLowerCase.endsWith("xml")) { result = new XmlMapper().writeValueAsString(content); } } catch (JsonProcessingException e) { LOG.error("Failed to serialize body with mediaType " + mediaType, e); } if (result == null) { result = content.toString(); } return result; } private  ContentUtils(); static String serializeContent(Object content, String mediaType); static String expandContentType(String format);  }
@Test public void serializeContent() throws Exception { Map map = ImmutableMap.of("test", "1", "test2", 2); assertNull(ContentUtils.serializeContent(null, null)); assertNull(ContentUtils.serializeContent(null, "application/json")); String content = ContentUtils.serializeContent(map, "application/json"); assertNotNull(Json.mapper().reader().readTree(content)); content = ContentUtils.serializeContent(map, "application/yaml"); assertNotNull(Yaml.mapper().reader().readTree(content)); content = ContentUtils.serializeContent(map, "text/xml"); assertNotNull(new XmlMapper().reader().readTree(content)); content = ContentUtils.serializeContent(map, "some/type"); assertEquals(content, map.toString()); }