List of usage examples for com.fasterxml.jackson.databind ObjectMapper setSerializationInclusion
public ObjectMapper setSerializationInclusion(JsonInclude.Include incl)
From source file:org.opencb.opencga.app.cli.main.OpenCGAMainOld.java
private StringBuilder createOutput(OptionsParser.CommonOptions commonOptions, List list, StringBuilder sb) throws JsonProcessingException { if (sb == null) { sb = new StringBuilder(); }/*from w w w . j av a 2s . co m*/ String idSeparator = null; switch (commonOptions.outputFormat) { case IDS: idSeparator = idSeparator == null ? "\n" : idSeparator; case ID_CSV: idSeparator = idSeparator == null ? "," : idSeparator; case ID_LIST: idSeparator = idSeparator == null ? "," : idSeparator; { if (!list.isEmpty()) { try { Iterator iterator = list.iterator(); Object next = iterator.next(); if (next instanceof QueryResult) { createOutput(commonOptions, (QueryResult) next, sb); } else { sb.append(getId(next)); } while (iterator.hasNext()) { next = iterator.next(); if (next instanceof QueryResult) { sb.append(idSeparator); createOutput(commonOptions, (QueryResult) next, sb); } else { sb.append(idSeparator).append(getId(next)); } } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } break; } case NAME_ID_MAP: { if (!list.isEmpty()) { try { Iterator iterator = list.iterator(); Object object = iterator.next(); if (object instanceof QueryResult) { createOutput(commonOptions, (QueryResult) object, sb); } else { sb.append(getName(object)).append(":").append(getId(object)); } while (iterator.hasNext()) { object = iterator.next(); if (object instanceof QueryResult) { sb.append(","); createOutput(commonOptions, (QueryResult) object, sb); } else { sb.append(",").append(getName(object)).append(":").append(getId(object)); } } } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) { e.printStackTrace(); } } break; } case RAW: if (list != null) { for (Object o : list) { sb.append(String.valueOf(o)); } } break; default: logger.warn("Unsupported output format \"{}\" for that query", commonOptions.outputFormat); case PRETTY_JSON: case PLAIN_JSON: JsonFactory factory = new JsonFactory(); ObjectMapper objectMapper = new ObjectMapper(factory); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); ObjectWriter objectWriter = commonOptions.outputFormat == OptionsParser.OutputFormat.PRETTY_JSON ? objectMapper.writerWithDefaultPrettyPrinter() : objectMapper.writer(); if (list != null && !list.isEmpty()) { Iterator iterator = list.iterator(); sb.append(objectWriter.writeValueAsString(iterator.next())); while (iterator.hasNext()) { sb.append("\n").append(objectWriter.writeValueAsString(iterator.next())); } } break; } return sb; }
From source file:com.masstransitproject.crosstown.serialization.JsonMessageSerializer.java
@Override public void serialize(OutputStream stream, T message, SendContext<T> ctx) throws IOException { _log.info("Serializing object " + message + "of type " + message.getClass()); Envelope evp = new Envelope(message, ctx.getMessageTypes()); evp.setMessageId(ctx.getMessageId()); ObjectMapper ObjectMapper = new ObjectMapper(); ObjectMapper.setSerializationInclusion(Include.NON_NULL); ObjectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); ObjectMapper.writeValue(stream, evp); }
From source file:org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.java
/** * Configure an existing {@link ObjectMapper} instance with this builder's * settings. This can be applied to any number of {@code ObjectMappers}. * @param objectMapper the ObjectMapper to configure *///ww w.j a v a 2 s . co m public void configure(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "ObjectMapper must not be null"); if (this.findModulesViaServiceLoader) { // Jackson 2.2+ objectMapper.registerModules(ObjectMapper.findModules(this.moduleClassLoader)); } else if (this.findWellKnownModules) { registerWellKnownModulesIfAvailable(objectMapper); } if (this.modules != null) { for (Module module : this.modules) { // Using Jackson 2.0+ registerModule method, not Jackson 2.2+ registerModules objectMapper.registerModule(module); } } if (this.moduleClasses != null) { for (Class<? extends Module> module : this.moduleClasses) { objectMapper.registerModule(BeanUtils.instantiateClass(module)); } } if (this.dateFormat != null) { objectMapper.setDateFormat(this.dateFormat); } if (this.locale != null) { objectMapper.setLocale(this.locale); } if (this.timeZone != null) { objectMapper.setTimeZone(this.timeZone); } if (this.annotationIntrospector != null) { objectMapper.setAnnotationIntrospector(this.annotationIntrospector); } if (this.propertyNamingStrategy != null) { objectMapper.setPropertyNamingStrategy(this.propertyNamingStrategy); } if (this.defaultTyping != null) { objectMapper.setDefaultTyping(this.defaultTyping); } if (this.serializationInclusion != null) { objectMapper.setSerializationInclusion(this.serializationInclusion); } if (this.filters != null) { objectMapper.setFilterProvider(this.filters); } for (Class<?> target : this.mixIns.keySet()) { objectMapper.addMixIn(target, this.mixIns.get(target)); } if (!this.serializers.isEmpty() || !this.deserializers.isEmpty()) { SimpleModule module = new SimpleModule(); addSerializers(module); addDeserializers(module); objectMapper.registerModule(module); } customizeDefaultFeatures(objectMapper); for (Object feature : this.features.keySet()) { configureFeature(objectMapper, feature, this.features.get(feature)); } if (this.handlerInstantiator != null) { objectMapper.setHandlerInstantiator(this.handlerInstantiator); } else if (this.applicationContext != null) { objectMapper.setHandlerInstantiator( new SpringHandlerInstantiator(this.applicationContext.getAutowireCapableBeanFactory())); } }
From source file:org.openecomp.sdnc.sli.aai.AAIService.java
public static ObjectMapper getObjectMapper() { ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); AnnotationIntrospector secondary = new JacksonAnnotationIntrospector(); mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(introspector, secondary)); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setSerializationInclusion(Include.NON_NULL); return mapper; }
From source file:org.apache.usergrid.android.sdk.UGClient.java
/** * Forms and initiates a raw synchronous http request and processes the response. * * @param httpMethod the HTTP method in the format: * HTTP_METHOD_<method_name> (e.g. HTTP_METHOD_POST) * @param params the URL parameters to append to the request URL * @param data the body of the request * @param segments additional URL path segments to append to the request URL * @return ApiResponse object//from w ww . ja v a2 s .c om */ public ApiResponse doHttpRequest(String httpMethod, Map<String, Object> params, Object data, String... segments) { ApiResponse response = null; OutputStream out = null; InputStream in = null; HttpURLConnection conn = null; String urlAsString = path(apiUrl, segments); try { String contentType = "application/json"; if (httpMethod.equals(HTTP_METHOD_POST) && isEmpty(data) && !isEmpty(params)) { data = encodeParams(params); contentType = "application/x-www-form-urlencoded"; } else { urlAsString = addQueryParams(urlAsString, params); } //logTrace("Invoking " + httpMethod + " to '" + urlAsString + "'"); URL url = new URL(urlAsString); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(httpMethod); conn.setRequestProperty("Content-Type", contentType); conn.setUseCaches(false); if ((accessToken != null) && (accessToken.length() > 0)) { String authStr = "Bearer " + accessToken; conn.setRequestProperty("Authorization", authStr); } conn.setDoInput(true); if (httpMethod.equals(HTTP_METHOD_POST) || httpMethod.equals(HTTP_METHOD_PUT)) { if (isEmpty(data)) { data = JsonNodeFactory.instance.objectNode(); } String dataAsString = null; if ((data != null) && (!(data instanceof String))) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); dataAsString = objectMapper.writeValueAsString(data); } else { dataAsString = (String) data; } //logTrace("Posting/putting data: '" + dataAsString + "'"); byte[] dataAsBytes = dataAsString.getBytes(); conn.setRequestProperty("Content-Length", Integer.toString(dataAsBytes.length)); conn.setDoOutput(true); out = conn.getOutputStream(); out.write(dataAsBytes); out.flush(); out.close(); out = null; } in = conn.getInputStream(); if (in != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); sb.append('\n'); } String responseAsString = sb.toString(); //logTrace("response from server: '" + responseAsString + "'"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); response = (ApiResponse) objectMapper.readValue(responseAsString, ApiResponse.class); response.setRawResponse(responseAsString); response.setUGClient(this); } else { response = null; logTrace("no response body from server"); } //final int responseCode = conn.getResponseCode(); //logTrace("responseCode from server = " + responseCode); } catch (Exception e) { logError("Error " + httpMethod + " to '" + urlAsString + "'"); if (e != null) { e.printStackTrace(); logError(e.getLocalizedMessage()); } response = null; } catch (Throwable t) { logError("Error " + httpMethod + " to '" + urlAsString + "'"); if (t != null) { t.printStackTrace(); logError(t.getLocalizedMessage()); } response = null; } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } if (conn != null) { conn.disconnect(); } } catch (Exception ignored) { } } return response; }
From source file:com.squid.kraken.v4.api.core.analytics.AnalyticsServiceBaseImpl.java
/** * @param result// ww w . ja va 2s.c o m * @return */ private String writeVegalightSpecs(VegaliteSpecs specs) { ObjectMapper mapper = new ObjectMapper(); try { mapper.setSerializationInclusion(Include.NON_NULL); return mapper.writeValueAsString(specs); } catch (JsonProcessingException e) { throw new APIException("failed to write vegalite specs to JSON", e, true); } }