Tabnine Logo
ObjectMapper
Code IndexAdd Tabnine to your IDE (free)

How to use
ObjectMapper
in
com.fasterxml.jackson.databind

Best Java code snippets using com.fasterxml.jackson.databind.ObjectMapper (Showing top 20 results out of 45,657)

Refine searchRefine arrow

  • ObjectMapperSingleton
  • JmesPathExpression
  • JmesPathEvaluationVisitor
  • AcceptorPathMatcher
  • ObjectNode
  • JsonNode
  • ArrayNode
origin: Vedenin/useful-java-links

/**
 *  Example to readJson using TreeModel
 */
private static void readJson() throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  JsonNode rootNode = mapper.readValue("{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}", JsonNode.class);
  String message = rootNode.get("message").asText(); // get property message
  JsonNode childNode =  rootNode.get("place"); // get object Place
  String place = childNode.get("name").asText(); // get property name
  System.out.println(message + " " + place); // print "Hi World!"
}
origin: prestodb/presto

  @Test
  public void testDeserializationSerialization()
      throws IOException
  {
    ObjectMapper mapper = new ObjectMapper();

    for (String input : testInputs) {
      RangePartition partition = mapper.readValue(input, RangePartition.class);

      String serialized = mapper.writeValueAsString(partition);
      assertEquals(serialized, input);
    }
  }
}
origin: linlinjava/litemall

public static String parseString(String body, String field) {
  ObjectMapper mapper = new ObjectMapper();
  JsonNode node = null;
  try {
    node = mapper.readTree(body);
    JsonNode leaf = node.get(field);
    if (leaf != null)
      return leaf.asText();
  } catch (IOException e) {
    e.printStackTrace();
  }
  return null;
}
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();
JsonNode actualObj = mapper.readTree("{\"k1\":\"v1\"}");
origin: apache/zookeeper

public JsonOutputter() {
  mapper = new ObjectMapper();
  mapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
  mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
  mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
}
origin: opensourceBIM/BIMserver

public ObjectNode toJson() {
  ObjectMapper objectMapper = new ObjectMapper();
  ObjectNode result = objectMapper.createObjectNode();
  ObjectNode renderEngine = objectMapper.createObjectNode();
  result.set("renderEngine", renderEngine);
  renderEngine.put("name", renderEngineName);
  renderEngine.set("version", renderEngineVersion.toJson());
  ObjectNode ifcModel = objectMapper.createObjectNode();
  ObjectNode user = objectMapper.createObjectNode();
  ObjectNode settings = objectMapper.createObjectNode();
  ObjectNode deserializer = objectMapper.createObjectNode();
  ObjectNode system = objectMapper.createObjectNode();
  ArrayNode jobsArray = objectMapper.createArrayNode();
    ObjectNode jobNode = objectMapper.createObjectNode();
  ObjectNode processing = objectMapper.createObjectNode();
  ArrayNode geometry = objectMapper.createArrayNode();
    ObjectNode geometryNode = objectMapper.createObjectNode();
  ArrayNode skippedNodes = objectMapper.createArrayNode();
origin: Netflix/eureka

private void doInstanceInfoCompactEncodeDecode(AbstractEurekaJacksonCodec codec, boolean isJson) throws Exception {
  InstanceInfo instanceInfo = infoIterator.next();
  String encodedString = codec.getObjectMapper(InstanceInfo.class).writeValueAsString(instanceInfo);
  if (isJson) {
    JsonNode metadataNode = new ObjectMapper().readTree(encodedString).get("instance").get("metadata");
    assertThat(metadataNode, is(nullValue()));
  }
  InstanceInfo decodedValue = codec.getObjectMapper(InstanceInfo.class).readValue(encodedString, InstanceInfo.class);
  assertThat(decodedValue.getId(), is(equalTo(instanceInfo.getId())));
  assertThat(decodedValue.getMetadata().isEmpty(), is(true));
}
origin: opensourceBIM/BIMserver

ObjectMapper objectMapper = new ObjectMapper();
ObjectNode servicesJson = objectMapper.readValue(data, ObjectNode.class);
ArrayNode activeServices = (ArrayNode) servicesJson.get("active");
List<SNewServiceDescriptor> list = Collections.synchronizedList(new ArrayList<>());
ThreadPoolExecutor executor = new ThreadPoolExecutor(activeServices.size(), activeServices.size(), 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(activeServices.size()));
for (JsonNode activeService : activeServices) {
  String providerListUrl = activeService.get("listUrl").asText();
  executor.submit(new Runnable(){
origin: stackoverflow.com

 import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();
origin: spring-projects/spring-framework

@Override
@Nullable
public String[] decodeInputStream(InputStream content) throws IOException {
  return this.objectMapper.readValue(content, String[].class);
}
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: linlinjava/litemall

public static <T> T parseObject(String body, String field, Class<T> clazz) {
  ObjectMapper mapper = new ObjectMapper();
  JsonNode node = null;
  try {
    node = mapper.readTree(body);
    node = node.get(field);
    return mapper.treeToValue(node, clazz);
  } catch (IOException e) {
    e.printStackTrace();
  }
  return null;
}
origin: apache/pulsar

  @Override
  public LoadManagerReport deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
      throws IOException, JsonProcessingException {
    ObjectMapper mapper = ObjectMapperFactory.getThreadLocal();
    ObjectNode root = ObjectMapperFactory.getThreadLocal().readTree(jsonParser);
    if ((root.has("loadReportType") && root.get("loadReportType").asText().equals(LoadReport.loadReportType))
        || (root.has("underLoaded"))) {
      return mapper.readValue(root.toString(), LoadReport.class);
    } else {
      return mapper.readValue(root.toString(), LocalBrokerData.class);
    }
  }
}
origin: linlinjava/litemall

public static Integer parseInteger(String body, String field) {
  ObjectMapper mapper = new ObjectMapper();
  JsonNode node = null;
  try {
    node = mapper.readTree(body);
    JsonNode leaf = node.get(field);
    if (leaf != null)
      return leaf.asInt();
  } catch (IOException e) {
    e.printStackTrace();
  }
  return null;
}
origin: prestodb/presto

@Test
public void testHeartbeatStatsSerialization()
    throws Exception
{
  ObjectMapper objectMapper = new ObjectMapperProvider().get();
  Stats stats = new Stats(new URI("http://example.com"));
  String serialized = objectMapper.writeValueAsString(stats);
  JsonNode deserialized = objectMapper.readTree(serialized);
  assertFalse(deserialized.has("lastFailureInfo"));
  stats.recordFailure(new SocketTimeoutException("timeout"));
  serialized = objectMapper.writeValueAsString(stats);
  deserialized = objectMapper.readTree(serialized);
  assertFalse(deserialized.get("lastFailureInfo").isNull());
  assertEquals(deserialized.get("lastFailureInfo").get("type").asText(), SocketTimeoutException.class.getName());
}
origin: prestodb/presto

  @Test
  public void testJsonSerialization()
      throws Exception
  {
    TestingTypeManager typeManager = new TestingTypeManager();

    ObjectMapper mapper = new ObjectMapperProvider().get()
        .registerModule(new SimpleModule().addDeserializer(Type.class, new TestingTypeDeserializer(typeManager)));

    AllOrNoneValueSet all = AllOrNoneValueSet.all(HYPER_LOG_LOG);
    assertEquals(all, mapper.readValue(mapper.writeValueAsString(all), AllOrNoneValueSet.class));

    AllOrNoneValueSet none = AllOrNoneValueSet.none(HYPER_LOG_LOG);
    assertEquals(none, mapper.readValue(mapper.writeValueAsString(none), AllOrNoneValueSet.class));
  }
}
origin: Vedenin/useful-java-links

public  static void main(String[] args) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  JsonNode root = mapper.readTree(json);
  String author = root.at("/store/book/3/title").asText();
  System.out.println(author); // print ["Hello, Middle-earth! "]
  System.out.println();
  String jsonHiWorld = "{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}\"";
  String message = mapper.readTree(jsonHiWorld).at("/message").asText();
  String place = mapper.readTree(jsonHiWorld).at("/place/name").asText();
  System.out.println(message + " " + place); // print "Hi World!"
}
origin: prestodb/presto

@Test
public void testSerialization()
    throws Exception
{
  ObjectMapper objectMapper = new ObjectMapper();
  BingTile tile = fromCoordinates(1, 2, 3);
  String json = objectMapper.writeValueAsString(tile);
  assertEquals("{\"x\":1,\"y\":2,\"zoom\":3}", json);
  assertEquals(tile, objectMapper.readerFor(BingTile.class).readValue(json));
}
origin: stackoverflow.com

 SimpleModule module = new SimpleModule();
module.addSerializer(new ResultSetSerializer());

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);

[ . . . do the query . . . ]
ResultSet resultset = statement.executeQuery(query);

// Use the DataBind Api here
ObjectNode objectNode = objectMapper.createObjectNode();

// put the resultset in a containing structure
objectNode.putPOJO("results", resultset);

// generate all
objectMapper.writeValue(stringWriter, objectNode);
com.fasterxml.jackson.databindObjectMapper

Javadoc

ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model ( JsonNode), as well as related functionality for performing conversions. It is also highly customizable to work both with different styles of JSON content, and to support more advanced Object concepts such as polymorphism and Object identity. ObjectMapper also acts as a factory for more advanced ObjectReaderand ObjectWriter classes. Mapper (and ObjectReaders, ObjectWriters it constructs) will use instances of JsonParser and JsonGeneratorfor implementing actual reading/writing of JSON. Note that although most read and write methods are exposed through this class, some of the functionality is only exposed via ObjectReader and ObjectWriter: specifically, reading/writing of longer sequences of values is only available through ObjectReader#readValues(InputStream)and ObjectWriter#writeValues(OutputStream).

Simplest usage is of form:

 
final ObjectMapper mapper = new ObjectMapper(); // can use static singleton, inject: just make sure to reuse! 
MyValue value = new MyValue(); 
// ... and configure 
File newState = new File("my-stuff.json"); 
mapper.writeValue(newState, value); // writes JSON serialization of MyValue instance 
// or, read 
MyValue older = mapper.readValue(new File("my-older-stuff.json"), MyValue.class); 
// Or if you prefer JSON Tree representation: 
JsonNode root = mapper.readTree(newState); 
// and find values by, for example, using a  
com.fasterxml.jackson.core.JsonPointer expression: 
int age = root.at("/personal/age").getValueAsInt();  

The main conversion API is defined in ObjectCodec, so that implementation details of this class need not be exposed to streaming parser and generator classes. Usage via ObjectCodec is, however, usually only for cases where dependency to ObjectMapper is either not possible (from Streaming API), or undesireable (when only relying on Streaming API).

Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls. If configuration of a mapper instance is modified after first usage, changes may or may not take effect, and configuration calls themselves may fail. If you need to use different configuration, you have two main possibilities:

  • Construct and use ObjectReader for reading, ObjectWriter for writing. Both types are fully immutable and you can freely create new instances with different configuration using either factory methods of ObjectMapper, or readers/writers themselves. Construction of new ObjectReaders and ObjectWriters is a very light-weight operation so it is usually appropriate to create these on per-call basis, as needed, for configuring things like optional indentation of JSON.
  • If the specific kind of configurability is not available via ObjectReader and ObjectWriter, you may need to use multiple ObjectMapper instead (for example: you cannot change mix-in annotations on-the-fly; or, set of custom (de)serializers). To help with this usage, you may want to use method #copy() which creates a clone of the mapper with specific configuration, and allows configuration of the copied instance before it gets used. Note that #copy operation is as expensive as constructing a new ObjectMapper instance: if possible, you should still pool and reuse mappers if you intend to use them for multiple operations.

Note on caching: root-level deserializers are always cached, and accessed using full (generics-aware) type information. This is different from caching of referenced types, which is more limited and is done only for a subset of all deserializer types. The main reason for difference is that at root-level there is no incoming reference (and hence no referencing property, no referral information or annotations to produce differing deserializers), and that the performance impact greatest at root level (since it'll essentially cache the full graph of deserializers involved).

Notes on security: use "default typing" feature (see #enableDefaultTyping()) is a potential security risk, if used with untrusted content (content generated by untrusted external parties). If so, you may want to construct a custom TypeResolverBuilder implementation to limit possible types to instantiate, (using #setDefaultTyping).

Most used methods

  • <init>
    Copy-constructor, mostly used to support #copy.
  • readValue
  • writeValueAsString
    Method that can be used to serialize any Java value as a String. Functionally equivalent to calling
  • readTree
    Method to deserialize JSON content as tree expressed using set of JsonNode instances. Returns root o
  • configure
    Method for changing state of an on/off serialization feature for this object mapper.
  • registerModule
    Method for registering a module that can extend functionality provided by this mapper; for example,
  • writeValue
    Method that can be used to serialize any Java value as JSON output, using Writer provided. Note: met
  • convertValue
    Convenience method for doing two-step conversion from given value, into instance of given value type
  • setSerializationInclusion
    Method for setting defalt POJO property inclusion strategy for serialization.
  • writeValueAsBytes
    Method that can be used to serialize any Java value as a byte array. Functionally equivalent to call
  • writerWithDefaultPrettyPrinter
    Factory method for constructing ObjectWriter that will serialize objects using the default pretty pr
  • createObjectNode
    Note: return type is co-variant, as basic ObjectCodec abstraction can not refer to concrete node ty
  • writerWithDefaultPrettyPrinter,
  • createObjectNode,
  • writer,
  • getTypeFactory,
  • enable,
  • valueToTree,
  • disable,
  • treeToValue,
  • getFactory,
  • readerFor

Popular in Java

  • Creating JSON documents from java classes using gson
  • orElseThrow (Optional)
    Return the contained value, if present, otherwise throw an exception to be created by the provided s
  • startActivity (Activity)
  • getSharedPreferences (Context)
  • Charset (java.nio.charset)
    A charset is a named mapping between Unicode characters and byte sequences. Every Charset can decode
  • MessageFormat (java.text)
    Produces concatenated messages in language-neutral way. New code should probably use java.util.Forma
  • NoSuchElementException (java.util)
    Thrown when trying to retrieve an element past the end of an Enumeration or Iterator.
  • PriorityQueue (java.util)
    A PriorityQueue holds elements on a priority heap, which orders the elements according to their natu
  • Pattern (java.util.regex)
    Patterns are compiled regular expressions. In many cases, convenience methods such as String#matches
  • ZipFile (java.util.zip)
    This class provides random read access to a zip file. You pay more to read the zip file's central di
  • Top Vim plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now