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

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#enable() . 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: NativeController.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
@RequestMapping("setConfig")
public FullHttpResponse setConfig(Channel channel, FullHttpRequest request) throws Exception {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
  PDownConfigInfo configInfo = objectMapper.readValue(request.content().toString(Charset.forName("UTF-8")), PDownConfigInfo.class);
  PDownConfigInfo beforeConfigInfo = PDownConfigContent.getInstance().get();
  boolean proxyChange = (beforeConfigInfo.getProxyConfig() != null && configInfo.getProxyConfig() == null) ||
      (configInfo.getProxyConfig() != null && beforeConfigInfo.getProxyConfig() == null) ||
      (beforeConfigInfo.getProxyConfig() != null && !beforeConfigInfo.getProxyConfig().equals(configInfo.getProxyConfig())) ||
      (configInfo.getProxyConfig() != null && !configInfo.getProxyConfig().equals(beforeConfigInfo.getProxyConfig()));
  boolean localeChange = !configInfo.getLocale().equals(beforeConfigInfo.getLocale());
  BeanUtils.copyProperties(configInfo, beforeConfigInfo);
  if (localeChange) {
    DownApplication.INSTANCE.loadPopupMenu();
    DownApplication.INSTANCE.refreshBrowserMenu();
  }
  //检查到前置代理有变动重启MITM代理服务器
  if (proxyChange && PDownProxyServer.isStart) {
    new Thread(() -> {
      PDownProxyServer.close();
      PDownProxyServer.start(DownApplication.INSTANCE.PROXY_PORT);
    }).start();
  }
  PDownConfigContent.getInstance().save();
  return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
}
 
Example 2
Source File: LogicalPlanPersistence.java    From Bats with Apache License 2.0 6 votes vote down vote up
public LogicalPlanPersistence(DrillConfig conf, ScanResult scanResult, ObjectMapper mapper) {
  this.mapper = mapper;

  SimpleModule deserModule = new SimpleModule("LogicalExpressionDeserializationModule")
      .addDeserializer(LogicalExpression.class, new LogicalExpression.De(conf))
      .addDeserializer(SchemaPath.class, new SchemaPath.De());

  mapper.registerModule(deserModule);
  mapper.enable(SerializationFeature.INDENT_OUTPUT);
  mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
  mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
  mapper.configure(Feature.ALLOW_COMMENTS, true);
  mapper.setFilterProvider(new SimpleFilterProvider().setFailOnUnknownId(false));
  registerSubtypes(LogicalOperatorBase.getSubTypes(scanResult));
  registerSubtypes(StoragePluginConfigBase.getSubTypes(scanResult));
  registerSubtypes(FormatPluginConfigBase.getSubTypes(scanResult));
}
 
Example 3
Source File: JsonWebPage.java    From charles with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public JsonObject toJsonObject() throws JsonProcessingException {
    ObjectMapper jsonMapper = new ObjectMapper();
    jsonMapper.enable(SerializationFeature.INDENT_OUTPUT);
    JsonReader reader = Json.createReader(
                            new StringReader(
                                jsonMapper.writeValueAsString(page)
                            )
                        );
    JsonObject parsed =  reader.readObject();
    reader.close();
    JsonObjectBuilder job = Json.createObjectBuilder();
    job.add("id", page.getUrl());
    
for (Entry<String, JsonValue> entry : parsed.entrySet()) {
    job.add(entry.getKey(), entry.getValue());
}
    return job.build();
}
 
Example 4
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private ObjectMapper createObjectMapper() {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
  objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
  objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  objectMapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
  objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  objectMapper.setDateFormat(new RFC3339DateFormat());
  ThreeTenModule module = new ThreeTenModule();
  module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
  module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
  module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
  objectMapper.registerModule(module);
  JsonNullableModule jnm = new JsonNullableModule();
  objectMapper.registerModule(jnm);
  return objectMapper;
}
 
Example 5
Source File: ExampleJacksonReladomoBitemporalSerializerTest.java    From reladomo with Apache License 2.0 6 votes vote down vote up
@Test
    public void testInMemoryNoRelationships() throws Exception
    {
        String serialized = "{\n" +
                "  \"_rdoClassName\" : \"com.gs.fw.common.mithra.test.domain.BitemporalOrderItem\",\n" +
//                "  \"_rdoState\" : 20,\n" +
                "  \"id\" : 70459,\n" +
                "  \"orderId\" : 1,\n" +
                "  \"productId\" : 1,\n" +
                "  \"quantity\" : 20.0,\n" +
                "  \"originalPrice\" : 10.5,\n" +
                "  \"discountPrice\" : 10.5,\n" +
                "  \"state\" : \"In-Progress\",\n" +
                "  \"businessDate\" : 1567363437186\n" +
                "}\n";
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JacksonReladomoModule());
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        JavaType customClassCollection = mapper.getTypeFactory().constructCollectionLikeType(Serialized.class, BitemporalOrderItem.class);

        Serialized<BitemporalOrderItem> back = mapper.readValue(serialized, customClassCollection);
        BitemporalOrderItem wrapped = back.getWrapped();
        Assert.assertEquals(70459, wrapped.getId());
        Assert.assertEquals("In-Progress", wrapped.getState());
        Assert.assertEquals(BitemporalOrderItemFinder.processingDate().getInfinityDate(), wrapped.getProcessingDate());
    }
 
Example 6
Source File: DatabaseValidationTask.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private void writeResult(ValidationResult result, PrintWriter output) {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
  try {
    String content = objectMapper.writeValueAsString(result);
    output.write(content);
  } catch (JsonProcessingException e) {
    LOG.error("Failed to process ValidationResult as JSON", e);
  }
}
 
Example 7
Source File: ExampleJacksonReladomoSerializerListTest.java    From reladomo with Apache License 2.0 5 votes vote down vote up
protected SerializedList toSerializedString(String json) throws Exception
    {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JacksonReladomoModule());
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        JavaType customClassCollection = mapper.getTypeFactory().constructMapLikeType(SerializedList.class, Order.class, OrderList.class);

        return mapper.readValue(json, customClassCollection);
//        return mapper.readValue(json, new TypeReference<Serialized<Order>>() {});
//        return mapper.readValue(json, Serialized.class);
    }
 
Example 8
Source File: DataRequestResponse.java    From Sensor-Data-Logger with Apache License 2.0 5 votes vote down vote up
@JsonIgnore
public String toJson() {
    String jsonData = null;
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        jsonData = mapper.writeValueAsString(this);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return jsonData;
}
 
Example 9
Source File: DefaultMapperDecorator.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectMapper decorate(ObjectMapper mapper) {
    
    if (null == mapper) {
        throw new IllegalArgumentException("mapper cannot be null");
    }
    mapper.enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME);
    mapper.registerModule(new GuavaModule());
    mapper.registerModule(new JaxbAnnotationModule());
    
    registerAbstractTypes(mapper);
    
    return mapper;
}
 
Example 10
Source File: PrettyJson.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        String json = mapper.writerWithDefaultPrettyPrinter()
                    .writeValueAsString(mapper.readTree(System.in));

        print("%s", json);
    } catch (IOException e) {
        log.error("Failed parsing JSON.", e);
        print("%s", e);
    }
}
 
Example 11
Source File: Main.java    From next-api-v2-examples with MIT License 5 votes vote down vote up
public static String prettyPrintJSON(JsonNode node) throws JsonProcessingException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.enable(SerializationFeature.INDENT_OUTPUT);
  mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
  System.out.println(mapper.writer().writeValueAsString(node));
  return mapper.writer().writeValueAsString(node);
}
 
Example 12
Source File: WebConfig.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Bean
public ObjectMapper objectMapper() {
    final ObjectMapper objMapper = new ObjectMapper();
    objMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return objMapper;
}
 
Example 13
Source File: UnmarshallingTester.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static ObjectMapper getObjectMapper() {
	ObjectMapper om = new ObjectMapper();
	JaxbAnnotationIntrospector jai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
	om.setAnnotationIntrospector(jai);
	om.enable(SerializationFeature.INDENT_OUTPUT);
	return om;
}
 
Example 14
Source File: InterceptorManager.java    From botbuilder-java with MIT License 5 votes vote down vote up
private void readDataFromFile() throws IOException {
    File recordFile = getRecordFile(testName);
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    recordedData = mapper.readValue(recordFile, RecordedData.class);
    System.out.println("Total records " + recordedData.getNetworkCallRecords().size());
}
 
Example 15
Source File: JacksonAnnotationUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSerializingUsingJsonRootName_thenCorrect() throws JsonProcessingException {
    final UserWithRoot user = new UserWithRoot(1, "John");

    final ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
    final String result = mapper.writeValueAsString(user);

    assertThat(result, containsString("John"));
    assertThat(result, containsString("user"));
}
 
Example 16
Source File: GenerateMetricFilterPublisher.java    From lambda-monitoring with Apache License 2.0 5 votes vote down vote up
@Override
public int publishMetricFilters(Collection<MetricFilter> metricFilters) {
    log.info("Writing metric filters to output file: " + outputFile.getPath());
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    try {
        mapper.writeValue(outputFile, metricFilters);
    } catch (IOException e) {
        log.error("Error writing JSON to output file.", e);
    }
    return 0;
}
 
Example 17
Source File: ObjectAsIdTest.java    From typescript-generator with MIT License 5 votes vote down vote up
@Test
public void testJackson() throws JsonProcessingException {
    final TestObjectA testObjectA = new TestObjectA();
    final TestObjectB testObjectB = new TestObjectB();
    final TestObjectC<String> testObjectC = new TestObjectC<>("valueC");
    final TestObjectD testObjectD = new TestObjectD();
    final TestObjectE testObjectE = new TestObjectE();
    final Wrapper wrapper = new Wrapper();
    wrapper.testObjectA1 = testObjectA;
    wrapper.testObjectA2 = testObjectA;
    wrapper.testObjectB1 = testObjectB;
    wrapper.testObjectB2 = testObjectB;
    wrapper.testObjectC1 = testObjectC;
    wrapper.testObjectC2 = testObjectC;
    wrapper.testObjectD1 = testObjectD;
    wrapper.testObjectD2 = testObjectD;
    wrapper.testObjectE1 = testObjectE;
    wrapper.testObjectE2 = testObjectE;
    wrapper.testObjectE3 = testObjectE;
    final ObjectMapper objectMapper = Utils.getObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    final String json = objectMapper.writeValueAsString(wrapper);
    Assert.assertTrue(json.contains("\"testObjectA1\": \"id1\""));
    Assert.assertTrue(json.contains("\"testObjectA2\": \"id1\""));
    Assert.assertTrue(json.contains("\"testObjectB1\": {"));
    Assert.assertTrue(json.contains("\"testObjectB2\": \"id2\""));
    Assert.assertTrue(json.contains("\"testObjectC1\": {"));
    Assert.assertTrue(json.contains("\"testObjectC2\": \"id3\""));
    Assert.assertTrue(json.contains("\"testObjectD1\": \"id4\""));
    Assert.assertTrue(json.contains("\"testObjectD2\": \"id4\""));
    Assert.assertTrue(json.contains("\"testObjectE1\": \"id5\""));
    Assert.assertTrue(json.contains("\"testObjectE2\": {"));
    Assert.assertTrue(json.contains("\"testObjectE3\": {"));
}
 
Example 18
Source File: RankNetModelConverter.java    From ltr4l with Apache License 2.0 4 votes vote down vote up
@Override
public void write(SolrLTRModel model, Writer writer) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.enable(SerializationFeature.INDENT_OUTPUT);
  mapper.writeValue(writer, model);
}
 
Example 19
Source File: CrnkClient.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
protected ObjectMapper createDefaultObjectMapper() {
	ObjectMapper om = new ObjectMapper();
	om.enable(SerializationFeature.INDENT_OUTPUT);
	return om;
}
 
Example 20
Source File: EnumValueTest.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Test
public void testEnumTest() {
    // test enum value
    EnumTest enumTest = new EnumTest();
    enumTest.setEnumString(EnumTest.EnumStringEnum.LOWER);
    enumTest.setEnumInteger(EnumTest.EnumIntegerEnum.NUMBER_1);
    enumTest.setEnumNumber(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1);

    assertEquals(EnumTest.EnumStringEnum.UPPER.toString(), "UPPER");
    assertEquals(EnumTest.EnumStringEnum.UPPER.getValue(), "UPPER");
    assertEquals(EnumTest.EnumStringEnum.LOWER.toString(), "lower");
    assertEquals(EnumTest.EnumStringEnum.LOWER.getValue(), "lower");

    assertEquals(EnumTest.EnumIntegerEnum.NUMBER_1.toString(), "1");
    assertTrue(EnumTest.EnumIntegerEnum.NUMBER_1.getValue() == 1);
    assertEquals(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.toString(), "-1");
    assertTrue(EnumTest.EnumIntegerEnum.NUMBER_MINUS_1.getValue() == -1);

    assertEquals(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.toString(), "1.1");
    assertTrue(EnumTest.EnumNumberEnum.NUMBER_1_DOT_1.getValue() == 1.1);
    assertEquals(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.toString(), "-1.2");
    assertTrue(EnumTest.EnumNumberEnum.NUMBER_MINUS_1_DOT_2.getValue() == -1.2);

    try {
        // test serialization (object => json)
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
        ObjectWriter ow = mapper.writer();
        String json = ow.writeValueAsString(enumTest);
        assertEquals(json, "{\"enum_string\":\"lower\",\"enum_string_required\":null,\"enum_integer\":1,\"enum_number\":1.1,\"outerEnum\":null}");

        // test deserialization (json => object)
        EnumTest fromString = mapper.readValue(json, EnumTest.class);
        assertEquals(fromString.getEnumString().toString(), "lower");
        assertEquals(fromString.getEnumInteger().toString(), "1");
        assertEquals(fromString.getEnumNumber().toString(), "1.1");

    } catch (Exception e) {
        fail("Exception thrown during serialization/deserialzation of JSON: " + e.getMessage());
    }
}