com.fasterxml.jackson.databind.ObjectMapper.<init>()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(10.3k)|赞(0)|评价(0)|浏览(169)

本文整理了Java中com.fasterxml.jackson.databind.ObjectMapper.<init>()方法的一些代码示例,展示了ObjectMapper.<init>()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ObjectMapper.<init>()方法的具体详情如下:
包路径:com.fasterxml.jackson.databind.ObjectMapper
类名称:ObjectMapper
方法名:<init>

ObjectMapper.<init>介绍

[英]Default constructor, which will construct the default JsonFactory as necessary, use SerializerProvider as its SerializerProvider, and BeanSerializerFactory as its SerializerFactory. This means that it can serialize all standard JDK types, as well as regular Java Beans (based on method names and Jackson-specific annotations), but does not support JAXB annotations.
[中]默认构造函数将根据需要构造默认的JsonFactory,它使用SerializerProvider作为其SerializerProvider,使用BeanSerializerFactory作为其SerializerFactory。这意味着它可以序列化所有标准JDK类型以及常规JavaBean(基于方法名和特定于Jackson的注释),但不支持JAXB注释。

代码示例

代码示例来源:origin: spring-projects/spring-framework

public MappingJackson2MessageConverter() {
  this.objectMapper = new ObjectMapper();
  this.objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
  this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}

代码示例来源:origin: stackoverflow.com

ObjectMapper mapper = new ObjectMapper();
Person user = mapper.readValue("{\"name\": \"John\"}", Person.class);

System.out.println(user.name); //John

代码示例来源:origin: stackoverflow.com

final String json = "{\"objects\" : [\"One\", \"Two\", \"Three\"]}";

final JsonNode arrNode = new ObjectMapper().readTree(json).get("objects");
if (arrNode.isArray()) {
  for (final JsonNode objNode : arrNode) {
    System.out.println(objNode);
  }
}

代码示例来源:origin: apache/incubator-druid

private void loadProperties(String configFile)
 ObjectMapper jsonMapper = new ObjectMapper();
 try {
  props = jsonMapper.readValue(
    new File(configFile), JacksonUtils.TYPE_REFERENCE_MAP_STRING_STRING
  );
 routerUrl = props.get("router_url");
 if (routerUrl == null) {
  String routerHost = props.get("router_host");
  if (null != routerHost) {
   routerUrl = StringUtils.format("http://%s:%s", routerHost, props.get("router_port"));

代码示例来源:origin: apache/storm

StateConfig getStateConfig(Map<String, Object> topoConf) throws Exception {
  StateConfig stateConfig;
  String providerConfig;
  ObjectMapper mapper = new ObjectMapper();
  mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
  if (topoConf.containsKey(Config.TOPOLOGY_STATE_PROVIDER_CONFIG)) {
    providerConfig = (String) topoConf.get(Config.TOPOLOGY_STATE_PROVIDER_CONFIG);
    stateConfig = mapper.readValue(providerConfig, StateConfig.class);
  } else {
    stateConfig = new StateConfig();
  }
  return stateConfig;
}

代码示例来源:origin: stackoverflow.com

public void testJackson() throws IOException {  
  ObjectMapper mapper = new ObjectMapper(); 
  File from = new File("albumnList.txt"); 
  TypeReference<HashMap<String,Object>> typeRef 
      = new TypeReference<HashMap<String,Object>>() {};

  HashMap<String,Object> o = mapper.readValue(from, typeRef); 
  System.out.println("Got " + o); 
}

代码示例来源:origin: twosigma/beakerx

@Test
public void shouldConvertData() throws Exception {
 //given
 ObjectMapper mapper = new ObjectMapper();
 DisplayerDataMapper.Converter converter = data -> {
  String json = mapper.writeValueAsString(data);
  return mapper.readValue(json, Object.class);
 };
 DisplayerDataMapper.register(converter);
 //when
 Object convert = DisplayerDataMapper.convert(new Person("XXX", 22));
 //then
 Map personAsMap = (Map) convert;
 assertThat(personAsMap.get("name")).isEqualTo("XXX");
 assertThat(personAsMap.get("age")).isEqualTo(22);
}

代码示例来源:origin: apache/nifi

public TlsClientConfig createClientConfig() throws IOException {
  String configJsonIn = getConfigJsonIn();
  if (!StringUtils.isEmpty(configJsonIn)) {
    try (InputStream inputStream = inputStreamFactory.create(new File(configJsonIn))) {
      TlsClientConfig tlsClientConfig = new ObjectMapper().readValue(inputStream, TlsClientConfig.class);
      tlsClientConfig.initDefaults();
      return tlsClientConfig;
    }
  } else {
    TlsClientConfig tlsClientConfig = new TlsClientConfig();
    tlsClientConfig.setCaHostname(getCertificateAuthorityHostname());
    tlsClientConfig.setDn(getDn());
    tlsClientConfig.setDomainAlternativeNames(getDomainAlternativeNames());
    tlsClientConfig.setToken(getToken());
    tlsClientConfig.setPort(getPort());
    tlsClientConfig.setKeyStore(KEYSTORE + getKeyStoreType().toLowerCase());
    tlsClientConfig.setKeyStoreType(getKeyStoreType());
    tlsClientConfig.setTrustStore(TRUSTSTORE + tlsClientConfig.getTrustStoreType().toLowerCase());
    tlsClientConfig.setKeySize(getKeySize());
    tlsClientConfig.setKeyPairAlgorithm(getKeyAlgorithm());
    tlsClientConfig.setSigningAlgorithm(getSigningAlgorithm());
    return tlsClientConfig;
  }
}

代码示例来源:origin: stackoverflow.com

ObjectMapper mapper = new ObjectMapper();
 mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
 ObjectNode node = mapper.getNodeFactory().objectNode();
 node.put("field1", "Maël Hörz");
 System.out.println(mapper.writeValueAsString(node));

代码示例来源:origin: stackoverflow.com

@JsonIgnoreProperties({"foobar"})
public static class Foo {
  public String foo = "a";
  public String bar = "b";

  public String foobar = "c";
}

//Test code
ObjectMapper mapper = new ObjectMapper();
Foo foo = new Foo();
foo.foobar = "foobar";
foo.foo = "Foo";
String out = mapper.writeValueAsString(foo);
Foo f = mapper.readValue(out, Foo.class);

代码示例来源:origin: auth0/java-jwt

private JWTCreator(Algorithm algorithm, Map<String, Object> headerClaims, Map<String, Object> payloadClaims) throws JWTCreationException {
  this.algorithm = algorithm;
  try {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(ClaimsHolder.class, new PayloadSerializer());
    mapper.registerModule(module);
    mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
    headerJson = mapper.writeValueAsString(headerClaims);
    payloadJson = mapper.writeValueAsString(new ClaimsHolder(payloadClaims));
  } catch (JsonProcessingException e) {
    throw new JWTCreationException("Some of the Claims couldn't be converted to a valid JSON format.", e);
  }
}

代码示例来源:origin: Alluxio/alluxio

/**
 * Creates a new instance of {@link WebInterfaceAbstractMetricsServlet}.
 */
public WebInterfaceAbstractMetricsServlet() {
 mObjectMapper = new ObjectMapper().registerModule(new MetricsModule(TimeUnit.SECONDS,
     TimeUnit.MILLISECONDS, false));
}

代码示例来源:origin: zendesk/maxwell

private static ObjectMapper getMapper()
{
  if (mapper == null) {
    mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(RowMap.class, new RowMapDeserializer());
    mapper.registerModule(module);
  }
  return mapper;
}

代码示例来源:origin: org.apache.logging.log4j/log4j-core

@Test
  public void testFromJsonWithLog4jModule() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final boolean encodeThreadContextAsList = false;
    final SimpleModule module = new Log4jJsonModule(encodeThreadContextAsList, true, false, false);
    module.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer());
    mapper.registerModule(module);
    final StackTraceElement expected = new StackTraceElement("package.SomeClass", "someMethod", "SomeClass.java", 123);
    final String s = this.aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}");
    final StackTraceElement actual = mapper.readValue(s, StackTraceElement.class);
    Assert.assertEquals(expected, actual);
  }
}

代码示例来源:origin: apache/storm

private <T> void assertEqualsJsonResponse(Response expected, Response actual, Class<T> entityClass) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    T entityFromExpected = objectMapper.readValue((String) expected.getEntity(), entityClass);
    T actualFromExpected = objectMapper.readValue((String) expected.getEntity(), entityClass);
    assertEquals(entityFromExpected, actualFromExpected);

    assertEquals(expected.getStatus(), actual.getStatus());
    assertTrue(expected.getHeaders().equalsIgnoreValueOrder(actual.getHeaders()));
  }
}

代码示例来源:origin: Netflix/eureka

@GET
  @Path("statusoverrides")
  public Response getOverrides() throws Exception {
    Map<String, InstanceInfo.InstanceStatus> result = registry.overriddenInstanceStatusesSnapshot();

    ObjectMapper objectMapper = new ObjectMapper();
    String responseStr = objectMapper.writeValueAsString(result);
    return Response.ok(responseStr).build();
  }
}

代码示例来源:origin: apache/usergrid

f = new File( "exportOneAppWQuery.json" );
  = new TypeReference<HashMap<String,Object>>() {};
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> jsonMap = mapper.readValue(new FileReader( f ), typeRef);
Map collectionsMap = (Map)jsonMap.get("collections");
String collectionName = (String)collectionsMap.keySet().iterator().next();
List collection = (List)collectionsMap.get( collectionName );
  Map metadataMap = (Map)entityMap.get("Metadata");
  String entityName = (String)metadataMap.get("name");
  assertFalse( "junkRealName".equals( entityName ) );

代码示例来源:origin: apache/storm

StateConfig getStateConfig(Map stormConf) throws Exception {
  StateConfig stateConfig;
  String providerConfig;
  ObjectMapper mapper = new ObjectMapper();
  mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
  if (stormConf.containsKey(Config.TOPOLOGY_STATE_PROVIDER_CONFIG)) {
    providerConfig = (String) stormConf.get(Config.TOPOLOGY_STATE_PROVIDER_CONFIG);
    stateConfig = mapper.readValue(providerConfig, StateConfig.class);
  } else {
    stateConfig = new StateConfig();
  }
  // assertion
  assertMandatoryParameterNotEmpty(stateConfig.hbaseConfigKey, "hbaseConfigKey");
  assertMandatoryParameterNotEmpty(stateConfig.tableName, "tableName");
  assertMandatoryParameterNotEmpty(stateConfig.columnFamily, "columnFamily");
  return stateConfig;
}

代码示例来源:origin: stackoverflow.com

String x = "{'candidateId':'k','candEducationId':1,'activitiesSocieties':'Activities for cand1'}";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
JsonNode df = mapper.readValue(x, JsonNode.class);
System.out.println(df.toString());
// output: {"candidateId":"k","candEducationId":1,"activitiesSocieties":"Activities for cand1"}

代码示例来源:origin: stackoverflow.com

final String json = "{\"date\" : \"2013-05-11\",\"value\" : 123}";

final ObjectMapper mapper = new ObjectMapper()
    .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
final List<Point> points = mapper.readValue(json,
    new TypeReference<List<Point>>() {
    });
System.out.println(points);

相关文章

微信公众号

最新文章

更多

ObjectMapper类方法