protected List<PackageMetadata> deserializeFromIndexFiles(List<File> indexFiles) { List<PackageMetadata> packageMetadataList = new ArrayList<>(); YAMLMapper yamlMapper = new YAMLMapper(); yamlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); for (File indexFile : indexFiles) { try { MappingIterator<PackageMetadata> it = yamlMapper.readerFor(PackageMetadata.class).readValues(indexFile); while (it.hasNextValue()) { PackageMetadata packageMetadata = it.next(); packageMetadataList.add(packageMetadata); } } catch (IOException e) { throw new IllegalArgumentException("Can't parse Release manifest YAML", e); } } return packageMetadataList; }
@Inject public CommentUserEventService(Duniter4jClient client, PluginSettings settings, CryptoService cryptoService, UserService userService, UserEventService userEventService) { super("duniter.user.event.comment", client, settings, cryptoService); this.userService = userService; this.userEventService = userEventService; objectMapper = JacksonUtils.newObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); this.changeListenSources = ImmutableList.of( new ChangeSource(MarketIndexDao.INDEX, MarketCommentDao.TYPE), new ChangeSource(RegistryIndexDao.INDEX, RegistryCommentDao.TYPE)); ChangeService.registerListener(this); this.trace = logger.isTraceEnabled(); this.recordType = RecordDao.TYPE; }
@JsonIgnore public List<AppStatus> getAppStatusList() { try { ObjectMapper mapper = new ObjectMapper(); mapper.addMixIn(AppStatus.class, AppStatusMixin.class); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); SimpleModule module = new SimpleModule("CustomModel", Version.unknownVersion()); SimpleAbstractTypeResolver resolver = new SimpleAbstractTypeResolver(); resolver.addMapping(AppInstanceStatus.class, AppInstanceStatusImpl.class); module.setAbstractTypes(resolver); mapper.registerModule(module); TypeReference<List<AppStatus>> typeRef = new TypeReference<List<AppStatus>>() { }; if (this.platformStatus != null) { return mapper.readValue(this.platformStatus, typeRef); } return new ArrayList<AppStatus>(); } catch (Exception e) { throw new IllegalArgumentException("Could not parse Skipper Platfrom Status JSON:" + platformStatus, e); } }
public ObjectMapper provideObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); objectMapper.setSerializationInclusion(Include.NON_NULL); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.setDateFormat(provideDateFormat()); return objectMapper; }
@Override protected String doInBackground(Void... params) { ObjectMapper objectMapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES).disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES); String comentarioJSON=""; //Construyo el JSON try { comentarioJSON = objectMapper.writeValueAsString(comentario); } catch (JsonProcessingException e) { e.printStackTrace(); } String resultado = null; //Cojo el resultado en un String resultado = ConsultasBBDD.hacerConsulta(ConsultasBBDD.insertaComentario, comentarioJSON, "POST"); return resultado; }
protected RestTemplate getRestTemplate() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.registerModule(new Jackson2HalModule()); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON)); converter.setObjectMapper(mapper); return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter)); }
public DefaultLicenseManager(String publicKey) { this.currentVersion = DefaultLicenseManager.LicenseVersion.PRODUCT_SIGNATURE_VERSION; this.registeredProducts = new LinkedList(); this.loadedLicenses = new HashMap(); this.productToActiveLicenseMap = new HashMap(); this.productToStarterLicenseMap = new HashMap(); this.licenseManagerListeners = new LinkedList(); try { X509EncodedKeySpec e = new X509EncodedKeySpec(Base.decode(publicKey == null?"H4sIAAAAAAAAAAEmAdn+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA58/mQ8VjKWDj9ai3mTzFX0b2S0VbV7LIQFv97U8ePdFoLu/cAcTvw7jsvQAT/3RHS7kzXXOk4OGDb7rmL85Dw6nfDs1jFA1auvrICW2vvOdpLrOOijJX5S5EJWHxKoBXSOfxU/fKFa93iuSVKJdqXJeah2Lgs/wq54BBcp4SrxogwWiuqFImqDo7BZKAZgLSm/v2IlICxKGM9QgAoYYLL/bongBpp6SxTy1gm/YD108jJxEk5wuFefDPDMlP0kioSsmGonU6o++pqYLuLkbFdNOdbmtoTphzP5vNaLaTQBmw9vuFHqh80BmIEQi6pK/Wz2RjOU6CYDpn9wv1Lgo2JQIDAQABbOI6ryYBAAA=":publicKey)); KeyFactory kf = KeyFactory.getInstance("RSA"); this.publicKey = kf.generatePublic(e); } catch (InvalidKeySpecException | IOException | NoSuchAlgorithmException var4) { throw new IllegalStateException("PublicKey could not be initialized.", var4); } this.jsonObjectMapper = new ObjectMapper(); this.licenseAnnotationValidator = new LicenseAnnotationValidator(this); this.jsonObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); }
public static SecurityAnalysisResult read(Path jsonFile) { Objects.requireNonNull(jsonFile); try (InputStream is = Files.newInputStream(jsonFile)) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); SimpleModule module = new SimpleModule(); module.addDeserializer(SecurityAnalysisResult.class, new SecurityAnalysisResultDeserializer()); module.addDeserializer(NetworkMetadata.class, new NetworkMetadataDeserializer()); module.addDeserializer(PostContingencyResult.class, new PostContingencyResultDeserializer()); module.addDeserializer(LimitViolationsResult.class, new LimitViolationResultDeserializer()); module.addDeserializer(LimitViolation.class, new LimitViolationDeserializer()); module.addDeserializer(Contingency.class, new ContingencyDeserializer()); module.addDeserializer(ContingencyElement.class, new ContingencyElementDeserializer()); objectMapper.registerModule(module); return objectMapper.readValue(is, SecurityAnalysisResult.class); } catch (IOException e) { throw new UncheckedIOException(e); } }
@Before public void setUp() throws Exception { mapper = Jackson2ObjectMapperBuilder.json() .featuresToDisable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .build(); mapper.findAndRegisterModules(); }
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); }
private void configureerMapper() { // Configuratie this.disable(MapperFeature.AUTO_DETECT_CREATORS); this.disable(MapperFeature.AUTO_DETECT_FIELDS); this.disable(MapperFeature.AUTO_DETECT_GETTERS); this.disable(MapperFeature.AUTO_DETECT_IS_GETTERS); this.disable(MapperFeature.AUTO_DETECT_SETTERS); // Default velden niet als JSON exposen (expliciet annoteren!) setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.NONE); this.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY); this.enable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS); // serialization this.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); setSerializationInclusion(JsonInclude.Include.NON_EMPTY); this.enable(SerializationFeature.WRITE_ENUMS_USING_INDEX); // deserialization this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); }
public static GenesisJson loadGenesisJson(InputStream genesisJsonIS) throws RuntimeException { String json = null; try { json = new String(ByteStreams.toByteArray(genesisJsonIS)); ObjectMapper mapper = new ObjectMapper() .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES); GenesisJson genesisJson = mapper.readValue(json, GenesisJson.class); return genesisJson; } catch (Exception e) { Utils.showErrorAndExit("Problem parsing genesis: "+ e.getMessage(), json); throw new RuntimeException(e.getMessage(), e); } }
public List<Account> getAccounts() { final Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); final ObjectMapper mapper = new ObjectMapper() .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); List<Account> accounts = null; try { accounts = mapper.readValue(rulesFile, new TypeReference<List<Account>>() {}); if (accounts != null) { accounts.forEach((account) -> { final Set<ConstraintViolation<Account>> accountViolations = validator.validate(account); if (accountViolations.size() > 0) { throw new AccountValidationException(accountViolations); } account.getRules().sort((o1, o2) -> o1.getType().compareTo(o2.getType())); }); } } catch (IOException ex) { Logger.getLogger(AccountService.class.getName()).log(Level.SEVERE, null, ex); } return accounts; }
@Override protected EpubPublication doInBackground(String... urls) { String strUrl = urls[0]; try { URL url = new URL(strUrl); URLConnection urlConnection = url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } Log.d("TestActivity", "EpubPublication => " + stringBuilder.toString()); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return objectMapper.readValue(stringBuilder.toString(), EpubPublication.class); } catch (IOException e) { Log.e(TAG, "SpineListTask error " + e); } return null; }
/** * Parses Json into type * @param str Entity content * @param clazz Class * @return Result */ @SneakyThrows public <U> U parseJson(String str, Class<U> clazz) { if (log.isInfoEnabled()) { if (log.isDebugEnabled()) { log.debug("Reading " + clazz.getSimpleName() + " from " + str); } else { String printStr = str; if (printStr.length() > 128) { printStr = printStr.substring(0, 128); } log.info("Reading " + clazz.getSimpleName() + " from " + printStr); } } ObjectMapper objectMapper = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); return objectMapper.readValue(str, clazz); }
protected <R extends Object> R readInternal(final DocumentDbPersistentEntity<?> entity, Class<R> type, final Document sourceDocument) { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { final DocumentDbPersistentProperty idProperty = entity.getIdProperty(); final Object idValue = sourceDocument.getId(); final JSONObject jsonObject = new JSONObject(sourceDocument.toJson()); if (idProperty != null) { // Replace the key id to the actual id field name in domain jsonObject.remove("id"); jsonObject.put(idProperty.getName(), idValue); } return objectMapper.readValue(jsonObject.toString(), type); } catch (IOException e) { throw new IllegalStateException("Failed to read the source document " + sourceDocument.toJson() + " to target type " + type, e); } }
@Override protected List<University> doInBackground(Void... voids) { String fileName = "university_sample.txt"; StringBuilder stringBuilder = new StringBuilder(); List<University> universities = null; try { // 1. Load data from local sample data file InputStream inputStream = mContext.getAssets().open(fileName); // 2. use Jackson library to map the JSON to List of University POJO ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); universities = Arrays.asList(mapper.readValue(inputStream, University[].class)); return universities; } catch (IOException e ) { e.printStackTrace(); return null; } }
public static ObjectMapper createDefaultMapper() { final ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); mapper.configure(SerializationFeature.INDENT_OUTPUT, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); SimpleModule module = new SimpleModule(); module.addSerializer(Transaction.class, new TransactionSerializer()); module.addDeserializer(Transaction.class, new TransactionDeserializer()); module.addSerializer(Difficulty.class, new DifficultySerializer()); module.addDeserializer(Difficulty.class, new DifficultyDeserializer()); module.addSerializer(Block.class, new BlockSerializer()); module.addDeserializer(Block.class, new BlockDeserializer()); mapper.registerModule(module); return mapper; }
private void configureFeature(Object feature, boolean enabled) { if (feature instanceof JsonParser.Feature) { this.objectMapper.configure((JsonParser.Feature) feature, enabled); } else if (feature instanceof JsonGenerator.Feature) { this.objectMapper.configure((JsonGenerator.Feature) feature, enabled); } else if (feature instanceof SerializationFeature) { this.objectMapper.configure((SerializationFeature) feature, enabled); } else if (feature instanceof DeserializationFeature) { this.objectMapper.configure((DeserializationFeature) feature, enabled); } else if (feature instanceof MapperFeature) { this.objectMapper.configure((MapperFeature) feature, enabled); } else { throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName()); } }
public ApiFactory(String baseUrl) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); this.okHttpClient = new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS) .connectTimeout(60, TimeUnit.SECONDS) .cookieJar(new SimpleCookieJar()) .addInterceptor(logging) .build(); this.retrofit = new Retrofit.Builder().baseUrl(baseUrl) .addConverterFactory(JacksonConverterFactory.create( new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE) .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY))) // 配置Json序列化的时候只使用field name,不走getter setter .client(okHttpClient) .build(); }
public Map<String, String> getDeploymentDataAsMap() { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); TypeReference<Map<String, String>> typeRef = new TypeReference<Map<String, String>>() { }; HashMap<String, String> result = mapper.readValue(this.deploymentData, typeRef); return result; } catch (Exception e) { throw new SkipperException("Could not parse appNameDeploymentIdMap JSON:" + this.deploymentData, e); } }
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); }
@Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(); jsonConverter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json")); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); objectMapper.registerModule(new Jackson2HalModule()); jsonConverter.setObjectMapper(objectMapper); return jsonConverter; }
@Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper; }
private static synchronized void buildDefaultObjectMapper() { objectMapper = new ObjectMapper(); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); // objectMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.setTimeZone(TimeZone.getDefault()); }
/** * Des-Serialize an object who was in json format * @param jsonObject * @return * @throws Exception */ public static CourseSession jsonDesSerialization(JsonNode jsonObject) throws Exception { CourseSession object; ObjectMapper mapper = new ObjectMapper(); DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); mapper.setDateFormat(myDateFormat); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); object = mapper.convertValue(jsonObject,CourseSession.class); return object; }
/** * get ObjectMapper entity. * @return ObjectMapper entity */ public static ObjectMapper getObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.setSerializationInclusion(Include.NON_NULL); return objectMapper; }
/** * Reads and parses the {@code package.json} content and returns with an assembled instance representing the content * of the file. * * @param packageLocation * the location of the {@code package.json} file. * * @return a new instance representing the content of the parsed file. */ static public PackageJson readValue(URI packageLocation) { try { ObjectMapper mapper = new ObjectMapper(new JsonPrettyPrinterFactory()); mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); return mapper.readValue(new File(packageLocation), PackageJson.class); } catch (Exception e) { throw new RuntimeException("Error while reading package.json from " + packageLocation + ".", e); } }
/** * 把bean对象转换为json字符串 * @param object bean对象 * @return string json字符串 */ public static String beanToJson(Object object){ ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String json = null; try { json = mapper.writeValueAsString(object); } catch (JsonProcessingException e) { logger.error("bean转换json出错",e); } return json; }
public static LoadFlowResult read(InputStream is) throws IOException { Objects.requireNonNull(is); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); SimpleModule module = new SimpleModule(); module.addDeserializer(LoadFlowResult.class, new LoadFlowResultDeserializer()); objectMapper.registerModule(module); return objectMapper.readValue(is, LoadFlowResult.class); }
/** * 允许单引号 * 允许不带引号的字段名称 */ public JsonMapper enableSimple() { this.configure(Feature.ALLOW_SINGLE_QUOTES, true); this.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); // 处理Date类型 this.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); this.setDateFormat(new java.text.SimpleDateFormat(DATE_PATTERN_DEFAULT)); this.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); return this; }
/** * Des-Serialize an object who was in json format * @param jsonObject * @return * @throws Exception */ public static Person jsonDesSerialization(JsonNode jsonObject) throws Exception { Person object; ObjectMapper mapper = new ObjectMapper(); DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); mapper.setDateFormat(myDateFormat); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); object = mapper.convertValue(jsonObject,Person.class); return object; }
@Primary @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false); return mapper; }
private static AnnotationQueries importAnnotationQueries(String annotationFile){ //initialize JSON-Object mapper ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); //use all fields mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); //only include not null & non empty fields mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); //store type of classess also mapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.NON_FINAL, "@class"); //ignore unknown properties mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS, false); mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false); AnnotationQueries q = null; try { q = mapper.readValue(new FileInputStream(new File(annotationFile)), AnnotationQueries.class); //read JSON from URL } catch (IOException e1) { e1.printStackTrace(); } return q; }
private static ObjectMapper newMapper() { mapper = new ObjectMapper(); mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper; }
public static ObjectMapper defaultObjectMapper() { return new XmlMapper(new XmlFactory(new WstxInputFactory(), new WstxPrefixedOutputFactory())) .enable(SerializationFeature.INDENT_OUTPUT) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true) .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY) .registerModule(new ParserModule()) .setAnnotationIntrospector(AnnotationIntrospector.pair( new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()), new JacksonAnnotationIntrospector())); }
@Provides @Singleton ObjectMapper provideObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setPropertyNamingStrategy( PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); return objectMapper; }
/** * Returns an ObjectReader with the project default settings. * @param features the list of DeserializationFeatures to be enabled, overwriting the project defaults * @return ObjectReader */ public static ObjectReader reader(DeserializationFeature... features) { if (features.length == 0) { return mapper.reader(); } else if (features.length == 1) { return mapper.reader(features[0]); } else { return mapper.reader(features[0], Arrays.copyOfRange(features, 1, features.length)); } }
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter jackson2HttpMessageConverter=new MappingJackson2HttpMessageConverter(); ObjectMapper mapper=jackson2HttpMessageConverter.getObjectMapper(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); mapper.setDateFormat(sdf); // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); //允许key没有使用双引号的json mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); //注册枚举反序列化时候忽略大小写 mapper.registerModule(JsonUtil.getEnumSimpleModule()); converters.add(jackson2HttpMessageConverter); super.configureMessageConverters(converters); }