Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#configure()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#configure() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CoreAppConfig.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Bean
public ObjectMapper jsonObjectMapper() {
	final ObjectMapper jsonMapper = new ObjectMapper();
	jsonMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	jsonMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
	jsonMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
	jsonMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);

	final SimpleModule module = new SimpleModule("FieldsMapping", Version.unknownVersion());
	module.setSerializerModifier(new BeanSerializerModifier() {
		@Override
		public JsonSerializer<?> modifyMapSerializer(final SerializationConfig config, final MapType valueType,
				final BeanDescription beanDesc, final JsonSerializer<?> serializer) {
			if (FieldsMap.class.isAssignableFrom(valueType.getRawClass())) {
				return new FieldsMapMixInLikeSerializer();
			} else {
				return super.modifyMapSerializer(config, valueType, beanDesc, serializer);
			}
		}
	});
	jsonMapper.registerModule(module);
	return jsonMapper;
}
 
Example 2
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void loadFromJson(Uri uri, String pwd) {
    sharedManager.setJsonExcep("");
    try {
        ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        InputStream is = context.getContentResolver().openInputStream(uri);
        WalletFile walletFile = objectMapper.readValue(is, WalletFile.class);
        credentials = Credentials.create(Wallet.decrypt(pwd, walletFile));
    } catch (JsonParseException jpe) {
        sharedManager.setJsonExcep("JsonParseException");
        jpe.printStackTrace();
    } catch (CipherException ce) {
        if (ce.getMessage().equals("Invalid password provided")) {
            sharedManager.setJsonExcep("WrongPassword");
        } else {
            sharedManager.setJsonExcep("CipherException");
        }
        ce.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 3
Source File: Jackson.java    From spring-boot-plus with Apache License 2.0 6 votes vote down vote up
/**
 * 键按自然顺序格式化输出
 *
 * @param object
 * @param prettyFormat
 * @return
 */
public static String toJsonString(Object object, boolean prettyFormat) {
    if (object == null) {
        return null;
    }
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        // 格式化输出
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, prettyFormat);
        // 键按自然顺序输出
        objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
        // 设置时区
        objectMapper.setTimeZone(timeZone);
        return objectMapper.writeValueAsString(object);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 4
Source File: JsonApiHttpMessageConverter.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public JsonApiHttpMessageConverter(Class<?>... classes) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    this.converter = new ResourceConverter(classes);
    this.converter.enableDeserializationOption(DeserializationFeature.ALLOW_UNKNOWN_INCLUSIONS);
}
 
Example 5
Source File: AbstractMockMvcTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
protected Release convertContentToRelease(String json) {
	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	try {
		return objectMapper.readValue(json, new TypeReference<Release>() {
		});
	}
	catch (IOException e) {
		throw new IllegalArgumentException("Can't parse JSON for Release", e);
	}
}
 
Example 6
Source File: SnapshotListCommand.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  try {
    ManagerApi managerApi = new ManagerApi(getApiClient());
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    System.out.println(mapper.writeValueAsString(managerApi.getAllSnapshotsInfo()));
  } catch (Exception ex) {
    if(printStackTrace) {
      ex.printStackTrace();
    } else {
      System.out.println(ex.getMessage());
    }
  }
}
 
Example 7
Source File: ContainerTest.java    From pegasus with Apache License 2.0 5 votes vote down vote up
@Test
public void deserializeContainer() throws IOException {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

    String test =
            "name: centos-pegasus\n"
                    + "type: docker\n"
                    + "image: docker:///rynge/montage:latest\n"
                    + "mounts: \n"
                    + "  - /Volumes/Work/lfs1:/shared-data/:ro\n"
                    + "  - /Volumes/Work/lfs12:/shared-data1/:ro\n"
                    + "profiles:\n"
                    + "  env:\n"
                    + "    JAVA_HOME: /opt/java/1.6";
    Container c = mapper.readValue(test, Container.class);
    assertNotNull(c);
    assertEquals(Container.TYPE.docker, c.getType());
    assertEquals("docker:///rynge/montage:latest", c.getImageURL().getURL());

    assertEquals(2, c.getMountPoints().size());
    assertThat(
            c.getMountPoints(), hasItem(new MountPoint("/Volumes/Work/lfs1:/shared-data/:ro")));
    assertThat(
            c.getMountPoints(), hasItem(new MountPoint("/Volumes/Work/lfs1:/shared-data/:ro")));

    List<Profile> profiles = c.getProfiles("env");
    assertThat(profiles, hasItem(new Profile("env", "JAVA_HOME", "/opt/java/1.6")));
}
 
Example 8
Source File: CqlTranslator.java    From clinical_quality_language with Apache License 2.0 5 votes vote down vote up
public String convertToJxson(Library library) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_DEFAULT);
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    JaxbAnnotationModule annotationModule = new JaxbAnnotationModule();
    mapper.registerModule(annotationModule);
    LibraryWrapper wrapper = new LibraryWrapper();
    wrapper.setLibrary(library);
    return mapper.writeValueAsString(wrapper);
}
 
Example 9
Source File: SecuritySyncEventProcessor.java    From egeria with Apache License 2.0 5 votes vote down vote up
private Object mapToObject(ResponseEntity<String> result, Class className) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    try {
        String resultString = sanitize(result.getBody());
        return mapper.readValue(resultString, className);
    } catch (IOException e) {
        log.error("403 {} - {}", e.getMessage(), e);
    }

    return null;
}
 
Example 10
Source File: TestUtil.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper createObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    mapper.registerModule(new JavaTimeModule());
    return mapper;
}
 
Example 11
Source File: JsonConfig.java    From nakadi with MIT License 5 votes vote down vote up
@Bean
@Primary
public ObjectMapper jacksonObjectMapper() {
    final ObjectMapper objectMapper = new ObjectMapper()
            .setPropertyNamingStrategy(SNAKE_CASE);

    objectMapper.registerModule(enumModule());
    objectMapper.registerModule(new Jdk8Module());
    objectMapper.registerModule(new ProblemModule());
    objectMapper.registerModule(new JodaModule());
    objectMapper.configure(WRITE_DATES_AS_TIMESTAMPS , false);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return objectMapper;
}
 
Example 12
Source File: ElasticsearchConfiguration.java    From 21-points with Apache License 2.0 5 votes vote down vote up
public CustomEntityMapper(ObjectMapper objectMapper) {
    this.objectMapper = objectMapper;
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, true);
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false);
    objectMapper.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, true);
}
 
Example 13
Source File: ConfigurationDataUtils.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper create() {
    ObjectMapper mapper = new ObjectMapper();
    // forward compatibility for the properties may go away in the future
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
    mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    return mapper;
}
 
Example 14
Source File: CustomerClient.java    From microservice-consul with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 15
Source File: SchemaSampler.java    From log-synth with Apache License 2.0 5 votes vote down vote up
public SchemaSampler(File input) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    init(mapper.readValue(input, new TypeReference<List<FieldSampler>>() {
    }));
}
 
Example 16
Source File: ApiClient.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public ApiClient() {
        objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
        objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
//        objectMapper.registerModule(new JodaModule());
        objectMapper.setDateFormat(ApiClient.buildDefaultDateFormat());

        dateFormat = ApiClient.buildDefaultDateFormat();
        rebuildHttpClient();
    }
 
Example 17
Source File: ElasticsearchSchemaFactory.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Override public Schema create(SchemaPlus parentSchema, String name,
    Map<String, Object> operand) {

  final Map map = (Map) operand;

  final ObjectMapper mapper = new ObjectMapper();
  mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

  try {

    List<HttpHost> hosts;

    if (map.containsKey("hosts")) {
      final List<String> configHosts = mapper.readValue((String) map.get("hosts"),
              new TypeReference<List<String>>() { });

      hosts = configHosts
              .stream()
              .map(host -> HttpHost.create(host))
              .collect(Collectors.toList());
    } else if (map.containsKey("coordinates")) {
      final Map<String, Integer> coordinates = mapper.readValue((String) map.get("coordinates"),
              new TypeReference<Map<String, Integer>>() { });

      hosts =  coordinates
              .entrySet()
              .stream()
              .map(entry -> new HttpHost(entry.getKey(), entry.getValue()))
              .collect(Collectors.toList());

      LOGGER.warn("Prefer using hosts, coordinates is deprecated.");
    } else {
      throw new IllegalArgumentException
      ("Both 'coordinates' and 'hosts' is missing in configuration. Provide one of them.");
    }
    final String pathPrefix = (String) map.get("pathPrefix");
    // create client
    final RestClient client = connect(hosts, pathPrefix);
    final String index = (String) map.get("index");

    return new ElasticsearchSchema(client, new ObjectMapper(), index);
  } catch (IOException e) {
    throw new RuntimeException("Cannot parse values from json", e);
  }
}
 
Example 18
Source File: LoginFailureHandlerConfig.java    From base-admin with MIT License 4 votes vote down vote up
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
    String msg = "{\"code\":\"400\",\"msg\":\"用户名或密码错误\"}";

    //判断api加密开关是否开启
    if("Y".equals(SysSettingUtil.getSysSetting().getSysApiEncrypt())){
        //加密
        try {
            //前端公钥
            String publicKey = httpServletRequest.getParameter("publicKey");

            log.info("前端公钥:" + publicKey);

            //jackson
            ObjectMapper mapper = new ObjectMapper();
            //jackson 序列化和反序列化 date处理
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            //每次响应之前随机获取AES的key,加密data数据
            String key = AesUtil.getKey();
            log.info("AES的key:" + key);
            log.info("需要加密的data数据:" + msg);
            String data = AesUtil.encrypt(msg, key);

            //用前端的公钥来解密AES的key,并转成Base64
            String aesKey = Base64.encodeBase64String(RsaUtil.encryptByPublicKey(key.getBytes(), publicKey));
            msg = "{\"data\":{\"data\":\"" + data + "\",\"aesKey\":\"" + aesKey + "\"}}";
        } catch (Throwable ee) {
            //输出到日志文件中
            log.error(ErrorUtil.errorInfoToString(ee));
        }
    }

    //转json字符串并转成Object对象,设置到Result中并赋值给返回值o
    httpServletResponse.setCharacterEncoding("UTF-8");
    httpServletResponse.setContentType("application/json; charset=utf-8");
    PrintWriter out = httpServletResponse.getWriter();
    out.print(msg);
    out.flush();
    out.close();
}
 
Example 19
Source File: ObjectMapperBuilder.java    From elasticactors with Apache License 2.0 4 votes vote down vote up
public final ObjectMapper build() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    // scan everything for META-INF/elasticactors.properties
    Set<String> basePackages = new HashSet<>();
    try {
        Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(RESOURCE_NAME);
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            Properties props = new Properties();
            props.load(url.openStream());
            basePackages.add(props.getProperty("basePackage"));
        }
    } catch(IOException e) {
        logger.warn("Failed to load elasticactors.properties", e);
    }

    // add other base packages
    if(this.basePackages != null && !"".equals(this.basePackages)) {
        String[] otherPackages = this.basePackages.split(",");
        basePackages.addAll(Arrays.asList(otherPackages));
    }

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

    for (String basePackage : basePackages) {
        configurationBuilder.addUrls(ClasspathHelper.forPackage(basePackage));
    }

    Reflections reflections = new Reflections(configurationBuilder);
    registerSubtypes(reflections, objectMapper);

    SimpleModule jacksonModule = new SimpleModule("org.elasticsoftware.elasticactors",new Version(1,0,0,null,null,null));

    registerCustomSerializers(reflections,jacksonModule);
    registerCustomDeserializers(reflections,jacksonModule);

    objectMapper.registerModule(jacksonModule);

    if(useAfterBurner) {
        // register the afterburner module to increase performance
        // afterburner does NOT work correctly with jackson version lower than 2.4.5! (if @JsonSerialize annotation is used)
        AfterburnerModule afterburnerModule = new AfterburnerModule();
        //afterburnerModule.setUseValueClassLoader(false);
        //afterburnerModule.setUseOptimizedBeanDeserializer(false);
        objectMapper.registerModule(afterburnerModule);
    }

    return objectMapper;
}
 
Example 20
Source File: PolicyViolation.java    From autorest-clientruntime-for-java with MIT License 3 votes vote down vote up
/**
 * Initializes a new instance of PolicyViolation.
 * @param type the error type
 * @param policyErrorInfo the error details
 * @throws JsonParseException if the policyErrorInfo has invalid content.
 * @throws JsonMappingException if the policyErrorInfo's JSON does not match the expected schema. 
 * @throws IOException if an IO error occurs.
 */
public PolicyViolation(String type, ObjectNode policyErrorInfo) throws JsonParseException, JsonMappingException, IOException {
    super(type, policyErrorInfo);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    this.policyErrorInfo = objectMapper.readValue(policyErrorInfo.toString(), PolicyViolationErrorInfo.class);
}