List of usage examples for com.fasterxml.jackson.databind ObjectMapper writeValueAsString
@SuppressWarnings("resource") public String writeValueAsString(Object value) throws JsonProcessingException
From source file:com.zxy.commons.json.JsonUtils.java
/** * ?json//www.j ava 2s .co m * * @param include include * @param object * @return json */ public static String toJson(JsonInclude.Include include, Object object) { try { ObjectMapper mapper = getObjectMapper(include); return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { throw new RuntimeException(e); } }
From source file:com.zxy.commons.json.JsonUtils.java
/** * map?json//from w ww . j a v a2 s. c o m * * @param <K> This is the key parameter * @param <V> This is the value parameter * @param include include * @param map map * @return json */ public static <K, V> String toJson(JsonInclude.Include include, Map<K, V> map) { try { ObjectMapper mapper = getObjectMapper(include); return mapper.writeValueAsString(map); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.mirth.connect.client.core.ConnectServiceUtil.java
public static int getNotificationCount(String serverId, String mirthVersion, Map<String, String> extensionVersions, Set<Integer> archivedNotifications, String[] protocols, String[] cipherSuites) {/*from www. j a va 2 s.c o m*/ CloseableHttpClient client = null; HttpPost post = new HttpPost(); CloseableHttpResponse response = null; int notificationCount = 0; try { ObjectMapper mapper = new ObjectMapper(); String extensionVersionsJson = mapper.writeValueAsString(extensionVersions); NameValuePair[] params = { new BasicNameValuePair("op", NOTIFICATION_COUNT_GET), new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion), new BasicNameValuePair("extensionVersions", extensionVersionsJson) }; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build(); post.setURI(URI.create(URL_CONNECT_SERVER + URL_NOTIFICATION_SERVLET)); post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8"))); HttpClientContext postContext = HttpClientContext.create(); postContext.setRequestConfig(requestConfig); client = getClient(protocols, cipherSuites); response = client.execute(post, postContext); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if ((statusCode == HttpStatus.SC_OK)) { HttpEntity responseEntity = response.getEntity(); Charset responseCharset = null; try { responseCharset = ContentType.getOrDefault(responseEntity).getCharset(); } catch (Exception e) { responseCharset = ContentType.TEXT_PLAIN.getCharset(); } List<Integer> notificationIds = mapper.readValue( IOUtils.toString(responseEntity.getContent(), responseCharset).trim(), new TypeReference<List<Integer>>() { }); for (int id : notificationIds) { if (!archivedNotifications.contains(id)) { notificationCount++; } } } } catch (Exception e) { } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); } return notificationCount; }
From source file:org.keycloak.helper.TestsHelper.java
public static String createClient(ClientRepresentation clientRepresentation) { ClientRegistration reg = ClientRegistration.create().url(keycloakBaseUrl, testRealm).build(); reg.auth(Auth.token(initialAccessCode)); try {//w ww . ja v a 2 s .com clientRepresentation = reg.create(clientRepresentation); registrationAccessCode = clientRepresentation.getRegistrationAccessToken(); ObjectMapper mapper = new ObjectMapper(); reg.auth(Auth.token(registrationAccessCode)); clientConfiguration = mapper .writeValueAsString(reg.getAdapterConfig(clientRepresentation.getClientId())); } catch (ClientRegistrationException e) { e.printStackTrace(); } catch (JsonProcessingException e) { e.printStackTrace(); } return clientConfiguration; }
From source file:com.mirth.connect.client.core.ConnectServiceUtil.java
public static List<Notification> getNotifications(String serverId, String mirthVersion, Map<String, String> extensionVersions, String[] protocols, String[] cipherSuites) throws Exception { CloseableHttpClient client = null;/*w ww . j a v a2s .c o m*/ HttpPost post = new HttpPost(); CloseableHttpResponse response = null; List<Notification> allNotifications = new ArrayList<Notification>(); try { ObjectMapper mapper = new ObjectMapper(); String extensionVersionsJson = mapper.writeValueAsString(extensionVersions); NameValuePair[] params = { new BasicNameValuePair("op", NOTIFICATION_GET), new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion), new BasicNameValuePair("extensionVersions", extensionVersionsJson) }; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build(); post.setURI(URI.create(URL_CONNECT_SERVER + URL_NOTIFICATION_SERVLET)); post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8"))); HttpClientContext postContext = HttpClientContext.create(); postContext.setRequestConfig(requestConfig); client = getClient(protocols, cipherSuites); response = client.execute(post, postContext); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if ((statusCode == HttpStatus.SC_OK)) { HttpEntity responseEntity = response.getEntity(); Charset responseCharset = null; try { responseCharset = ContentType.getOrDefault(responseEntity).getCharset(); } catch (Exception e) { responseCharset = ContentType.TEXT_PLAIN.getCharset(); } String responseContent = IOUtils.toString(responseEntity.getContent(), responseCharset).trim(); JsonNode rootNode = mapper.readTree(responseContent); for (JsonNode childNode : rootNode) { Notification notification = new Notification(); notification.setId(childNode.get("id").asInt()); notification.setName(childNode.get("name").asText()); notification.setDate(childNode.get("date").asText()); notification.setContent(childNode.get("content").asText()); allNotifications.add(notification); } } else { throw new ClientException("Status code: " + statusCode); } } catch (Exception e) { throw e; } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); } return allNotifications; }
From source file:org.commonjava.aprox.bind.jaxrs.util.ResponseUtils.java
public static Response formatCreatedResponseWithJsonEntity(final URI location, final Object dto, final ObjectMapper objectMapper) { if (dto == null) { return Response.noContent().build(); }/*from w w w .j a v a2 s.c om*/ Response response; try { response = Response.created(location).entity(objectMapper.writeValueAsString(dto)) .type(ApplicationContent.application_json).build(); } catch (final JsonProcessingException e) { response = formatResponse(e, "Failed to serialize DTO to JSON: " + dto, true); } return response; }
From source file:org.keycloak.helper.TestsHelper.java
public static String createDirectGrantClient() { ClientRepresentation clientRepresentation = new ClientRepresentation(); clientRepresentation.setClientId("test-dga"); clientRepresentation.setFullScopeAllowed(true); clientRepresentation.setPublicClient(Boolean.TRUE); clientRepresentation.setDirectAccessGrantsEnabled(true); ClientRegistration reg = ClientRegistration.create().url(keycloakBaseUrl, testRealm).build(); reg.auth(Auth.token(initialAccessCode)); try {/*from ww w. j av a 2 s . c o m*/ clientRepresentation = reg.create(clientRepresentation); registrationAccessCode = clientRepresentation.getRegistrationAccessToken(); ObjectMapper mapper = new ObjectMapper(); reg.auth(Auth.token(registrationAccessCode)); clientConfiguration = mapper .writeValueAsString(reg.getAdapterConfig(clientRepresentation.getClientId())); } catch (ClientRegistrationException e) { e.printStackTrace(); } catch (JsonProcessingException e) { e.printStackTrace(); } return clientConfiguration; }
From source file:com.netsteadfast.greenstep.util.SystemExpressionJobUtils.java
public static String getEncUploadOid(String accountId, String sysExprJobOid) throws ServiceException, Exception { if (StringUtils.isBlank(accountId) || StringUtils.isBlank(sysExprJobOid)) { throw new Exception("error, accountId or sysExprJobOid value is blank!"); }//from w w w . j a v a 2 s .co m Map<String, Object> dataMap = new HashMap<String, Object>(); dataMap.put("accountId", accountId); dataMap.put("sysExprJobOid", sysExprJobOid); ObjectMapper objectMapper = new ObjectMapper(); String jsonData = objectMapper.writeValueAsString(dataMap); String uploadOid = UploadSupportUtils.create(Constants.getSystem(), UploadTypes.IS_TEMP, false, jsonData.getBytes(), SimpleUtils.getUUIDStr() + ".json"); uploadOid = SimpleUtils.toHex( EncryptorUtils.encrypt(Constants.getEncryptorKey1(), Constants.getEncryptorKey2(), uploadOid)); return uploadOid; }
From source file:eu.trentorise.opendata.commons.test.jackson.TodJacksonTester.java
/** * Converts {@code obj} to an {@link ObjectNode}, sets field * {@code fieldName} to {@code newNode} and returns the json string * representation of such new object. Also logs the json with the provided * logger at FINE level./*from w ww. j av a2s .c o m*/ */ public static String changeField(ObjectMapper objectMapper, Logger logger, Object obj, String fieldName, JsonNode newNode) { checkNotNull(obj); checkNotEmpty(fieldName, "Invalid field name!"); String string; try { string = objectMapper.writeValueAsString(obj); } catch (JsonProcessingException ex) { throw new RuntimeException("Error while jacksonizing object to json node!", ex); } TreeNode treeNode; try { treeNode = (ObjectNode) objectMapper.readTree(string); } catch (IOException ex) { throw new RuntimeException("Error while creating json tree from serialized object:" + string, ex); } if (!treeNode.isObject()) { throw new TodException( "The provided object was jacksonized to a string which does not represent a JSON object! String is " + string); } ObjectNode jo = (ObjectNode) treeNode; jo.put(fieldName, newNode); String json = jo.toString(); logger.log(Level.FINE, "converted json = {0}", json); return json; }
From source file:io.orchestrate.client.ResponseConverterUtil.java
@SuppressWarnings("unchecked") public static <T> T jsonToDomainObject(ObjectMapper mapper, JsonNode json, Class<T> clazz) throws IOException { if (clazz == null || clazz == Void.class || json == null || json.isNull()) { return null; }/*from w w w . jav a 2 s . co m*/ if (clazz.equals(String.class)) { return (T) mapper.writeValueAsString(json); } return mapper.treeToValue(json, clazz); }