@Test @SuppressWarnings({"rawtypes", "unchecked"}) public void annotationStyleMoshi1ProducesMoshi1Annotations() throws ClassNotFoundException, SecurityException, NoSuchMethodException, NoSuchFieldException { Class generatedType = schemaRule.generateAndCompile("/json/examples/torrent.json", "com.example", config("annotationStyle", "moshi1", "propertyWordDelimiters", "_", "sourceType", "json")) .loadClass("com.example.Torrent"); assertThat(schemaRule.getGenerateDir(), not(containsText("org.codehaus.jackson"))); assertThat(schemaRule.getGenerateDir(), not(containsText("com.fasterxml.jackson"))); assertThat(schemaRule.getGenerateDir(), not(containsText("com.google.gson"))); assertThat(schemaRule.getGenerateDir(), not(containsText("@SerializedName"))); assertThat(schemaRule.getGenerateDir(), containsText("com.squareup.moshi")); assertThat(schemaRule.getGenerateDir(), containsText("@Json")); Method getter = generatedType.getMethod("getBuild"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(nullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(nullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(nullValue())); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void customAnnotatorCanBeAppliedAlongsideCoreAnnotator() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("customAnnotator", DeprecatingAnnotator.class.getName())); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue())); assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue())); assertThat(generatedType.getAnnotation(Deprecated.class), is(notNullValue())); assertThat(getter.getAnnotation(Deprecated.class), is(notNullValue())); }
public JsonMapper() { // calls the default constructor super(); // configures ISO8601 formatter for date without time zone // the used format is 'yyyy-MM-dd' super.setDateFormat(new SimpleDateFormat(FMT_ISO_LOCAL_DATE)); // enforces to skip null and empty values in the serialized JSON output super.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); // enforces to skip null references in the serialized output of Map super.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); // enables serialization failures, when mapper encounters unknown properties names super.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); // configures the format to prevent writing of the serialized output for java.util.Date // instances as timestamps. any date should be written in ISO format super.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); }
/** * Convert an object to JSON byte array. * * @param object * the object to convert * @return the JSON byte array * @throws IOException */ public static byte[] convertObjectToJsonBytes(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); JavaTimeModule module = new JavaTimeModule(); module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE); module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE); module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE); module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE); module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE); mapper.registerModule(module); return mapper.writeValueAsBytes(object); }
private static ObjectMapper initializeMapper() { return new ObjectMapper() .registerModule(new JavaTimeModule()) .disable(MapperFeature.AUTO_DETECT_GETTERS) .disable(MapperFeature.AUTO_DETECT_CREATORS) .disable(MapperFeature.AUTO_DETECT_SETTERS) .disable(MapperFeature.AUTO_DETECT_IS_GETTERS) .disable(MapperFeature.AUTO_DETECT_FIELDS) .disable(MapperFeature.DEFAULT_VIEW_INCLUSION) .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.NONE) .enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY) .enable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS) // serialization .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .enable(SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID) .setSerializationInclusion(JsonInclude.Include.NON_EMPTY) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // deserialization .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE); }
public SiloTemplateResolver(Class<T> classType) { ObjectMapper m = new ObjectMapper(); m.registerModule(new GuavaModule()); m.registerModule(new LogbackModule()); m.registerModule(new GuavaExtrasModule()); m.registerModule(new JodaModule()); m.registerModule(new JSR310Module()); m.registerModule(new AfterburnerModule()); m.registerModule(new FuzzyEnumModule()); m.setPropertyNamingStrategy(new AnnotationSensitivePropertyNamingStrategy()); m.setSubtypeResolver(new DiscoverableSubtypeResolver()); //Setup object mapper to ignore the null properties when serializing the objects m.setSerializationInclusion(JsonInclude.Include.NON_NULL); //Lets be nice and allow additional properties by default. Allows for more flexible forward/backward //compatibility and works well with jackson addtional properties feature for serialization m.configure(FAIL_ON_UNKNOWN_PROPERTIES, false); this.classType = classType; this.mapper = m; }
public static ObjectMapper objectMapper() { return new ObjectMapper() // Property visibility .setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS) .setDefaultVisibility(JsonAutoDetect.Value.construct(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC)) .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true) // Property naming and order .setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE) // Customised de/serializers // Formats, locals, encoding, binary data .setDateFormat(new SimpleDateFormat("MM/dd/yyyy")) .setDefaultPrettyPrinter(new DefaultPrettyPrinter()) .setLocale(Locale.CANADA); }
private JsonMapper() { // calls the default constructor super(); // configures ISO8601 formatter for date without time zone // the used format is 'yyyy-MM-dd' setDateFormat(new SimpleDateFormat(FMT_ISO_LOCAL_DATE)); // enforces to skip null and empty values in the serialized JSON output setSerializationInclusion(JsonInclude.Include.NON_EMPTY); // enforces to skip null references in the serialized output of map configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); // enables serialization failures, when mapper encounters unknown properties names configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // configures the format to prevent writing of the serialized output for dates // instances as timestamps; any date should be written in ISO format configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); }
@Override public void afterPropertiesSet() throws Exception { //Configure the objectMapper ready for use objectMapper = new ObjectMapper(); objectMapper.registerModule(module); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); //or NON_EMPTY? // this is deprecated in jackson 2.9 and there is no straight replacement // https://github.com/FasterXML/jackson-databind/issues/1547 objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); DateFormat DATE_FORMAT_ISO8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); DATE_FORMAT_ISO8601.setTimeZone(TimeZone.getTimeZone("UTC")); objectMapper.setDateFormat(DATE_FORMAT_ISO8601); objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); }
public static ObjectMapper createObjectMapper() { final YAMLFactory yamlFactory = new YAMLFactory() .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false) .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true) .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true) .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false); ObjectMapper mapper = new ObjectMapper(yamlFactory) .registerModule(new Jdk8Module()) .setSerializationInclusion(JsonInclude.Include.NON_EMPTY) .enable(SerializationFeature.INDENT_OUTPUT) .disable(SerializationFeature.WRITE_NULL_MAP_VALUES); for (Step step : ServiceLoader.load(Step.class, YamlHelpers.class.getClassLoader())) { mapper.registerSubtypes(new NamedType(step.getClass(), step.getKind())); } return mapper; }
private ObjectMapper createMapper(final boolean indent) { // final SimpleModule module = new SimpleModule(); // module.addSerializer(Double.class, new MyDoubleSerialiser()); final ObjectMapper mapper = new ObjectMapper(); // mapper.registerModule(module); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); mapper.configure(SerializationFeature.INDENT_OUTPUT, indent); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // Enabling default typing adds type information where it would otherwise be ambiguous, i.e. for abstract classes // mapper.enableDefaultTyping(); return mapper; }
public void parseExportedVariables(PrintStream logger, Run<?, ?> build, String output) throws IOException { if (exportVariablesString == null) { return; } if (exportVariablesString.trim().equals("")) { return; } logger.println("Transforming to environment variables: " + exportVariablesString); HashMap<String, String> exportVariablesNames = com.azure.azurecli.helpers.Utils.parseExportedVariables(exportVariablesString); HashMap<String, String> exportVariables = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); JsonNode rootNode = mapper.readTree(output); for (Map.Entry<String, String> var : exportVariablesNames.entrySet()) { String value = rootNode.at(var.getKey()).asText(); exportVariables.put(var.getValue(), value); } com.azure.azurecli.helpers.Utils.setEnvironmentVariables(build, exportVariables); }
/** * Initialize object mapper. * * @return the object mapper */ protected ObjectMapper initializeObjectMapper() { final ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); mapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC); mapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC); mapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); return mapper; }
public JacksonContextResolver() throws Exception { this.objectMapper = new ObjectMapper() .registerModule(new Jdk8Module()) .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) .configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true) .configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true); }
public void createState(BrowserSessionId browserSessionId, String matchingId, long timeoutMillis, BrowserSessionStateExtractionConfig browserSessionStateExtractionConfig) { Map<String, Object> params = ImmutableMap.of("optMatchingId", matchingId, "extractionConfig", browserSessionStateExtractionConfig); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); Optional<HttpResponse> r = sendPOST(createStateTemplate, ImmutableMap.of("browserSessionId", browserSessionId.toString()), mapper.valueToTree(params)).getOptHttpResponse(); waitForStateExtractionResponse(timeoutMillis, r); }
@Primary @Bean(name = "objectMapper") ObjectMapper objectMapper() { springHateoasObjectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); springHateoasObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); springHateoasObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); return springHateoasObjectMapper; }
@Bean @Primary public Jackson2ObjectMapperBuilder objectMapperBuilder() { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.serializationInclusion(JsonInclude.Include.NON_NULL); return builder; }
/** * Converts the POJO which represents the JSON payload into a JSON string. * null values will be ignored. */ public static String toJsonAsStringNonNull(Object object) throws IOException { assertNotNull(object); ObjectMapper om = new ObjectMapper(); om.setSerializationInclusion(JsonInclude.Include.NON_NULL); return om.writeValueAsString(object); }
@Bean public Jackson2ObjectMapperBuilder objectMapperBuilder() { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.serializationInclusion(JsonInclude.Include.NON_NULL); builder.indentOutput(true); return builder; }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void defaultAnnotationStyeIsJackson2() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example"); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); Method getter = generatedType.getMethod("getA"); assertThat(generatedType.getAnnotation(JsonPropertyOrder.class), is(notNullValue())); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(getter.getAnnotation(JsonProperty.class), is(notNullValue())); }
@JsonInclude(JsonInclude.Include.NON_NULL) public Object getValues() { if (valuesRef != null) { return valuesRef; } else if (values != null) { return values; } return null; }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void Jackson2InclusionLevelNonAbsent() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "jackson2", "inclusionLevel", "NON_ABSENT")); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(((JsonInclude) generatedType.getAnnotation(JsonInclude.class)).value(), is(JsonInclude.Include.NON_ABSENT)); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void Jackson2InclusionLevelNonNull() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "jackson2", "inclusionLevel", "NON_NULL")); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(((JsonInclude) generatedType.getAnnotation(JsonInclude.class)).value(), is(JsonInclude.Include.NON_NULL)); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void Jackson2InclusionLevelUseDefault() throws ClassNotFoundException, SecurityException, NoSuchMethodException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("annotationStyle", "jackson2", "inclusionLevel", "USE_DEFAULTS")); Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties"); assertThat(generatedType.getAnnotation(JsonInclude.class), is(notNullValue())); assertThat(((JsonInclude) generatedType.getAnnotation(JsonInclude.class)).value(), is(JsonInclude.Include.USE_DEFAULTS)); }
/** * Convert an object to JSON byte array. * * @param object * the object to convert * @return the JSON byte array * @throws IOException */ public static byte[] convertObjectToJsonBytes(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); JavaTimeModule module = new JavaTimeModule(); mapper.registerModule(module); return mapper.writeValueAsBytes(object); }
private CustomizationObjectMapper (DateFormat dateFormat) { super(); // 设置格式化 setDateFormat( dateFormat ); // <code>null<code> 不序列化 setSerializationInclusion( JsonInclude.Include.NON_NULL ); }
private String getErrors(TransformException exception) throws JsonProcessingException { ObjectWriter jsonObjectWriter = new ObjectMapper() .setSerializationInclusion(JsonInclude.Include.NON_NULL) .writer() .withDefaultPrettyPrinter(); return jsonObjectWriter.writeValueAsString(exception.getDetails()); }
/** * Write out the errors to a file. * * @param allErrors The errors to write. * @param outFile The location to write. */ private void writeOutErrors(AllErrors allErrors, Path outFile) { try (Writer writer = Files.newBufferedWriter(outFile)) { ObjectWriter jsonObjectWriter = new ObjectMapper() .setSerializationInclusion(JsonInclude.Include.NON_NULL) .writer() .withDefaultPrettyPrinter(); jsonObjectWriter.writeValue(writer, allErrors); } catch (IOException exception) { DEV_LOG.error("Could not write out error JSON to file", exception); } }
@Bean @Primary public ObjectMapper objectMapper() { return new ObjectMapper() .registerModule(new Jdk8Module()) .registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES)) .registerModule(new JavaTimeModule()).disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .setSerializationInclusion(JsonInclude.Include.NON_EMPTY) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); }
@JsonInclude(JsonInclude.Include.NON_DEFAULT) public List<String> getExtensions() { if (extensions == null) { // when loading an old JSONFormatConfig that doesn't contain an "extensions" attribute return DEFAULT_EXTS; } return extensions; }
@Bean public Jackson2ObjectMapperBuilder objectMapperBuilder() { return new Jackson2ObjectMapperBuilder() .failOnUnknownProperties(false) .indentOutput(true) .serializationInclusion(JsonInclude.Include.NON_NULL) .modulesToInstall( new Jdk8Module(), new JavaTimeModule() ); }
private static MappingJackson2JsonView createDelegatedView() { final MappingJackson2JsonView view = new MappingJackson2JsonView(); view.setPrettyPrint(true); view.setDisableCaching(true); view.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL).findAndRegisterModules(); return view; }