Home  Java   Java serial ...

Java serialization and deserialization process

Let’s break down what happens internally when you call:

Person p = mapper.readValue(json, Person.class);

and how a plain string (JSON) becomes a Java object.


🧩 Step-by-step Explanation (Inside ObjectMapper.readValue())

1️⃣ You call readValue(json, Person.class)


2️⃣ Jackson detects the data format

JsonParser parser = objectMapper.createParser(json);

3️⃣ JSON is parsed into tokens

Jackson doesn’t first build a big intermediate object — instead, it streams tokens like:

Example JSON:

{ "name": "Sagar", "age": 30 }

Jackson converts this into a stream of tokens:

START_OBJECT
FIELD_NAME "name"
VALUE_STRING "Sagar"
FIELD_NAME "age"
VALUE_NUMBER_INT 30
END_OBJECT

So it’s reading sequentially, like a tokenizer.


4️⃣ Jackson determines what type to build

This deserializer knows how to:


5️⃣ Object instantiation

Jackson creates an empty object — usually using:


6️⃣ Field mapping

As the parser reads each token:

Then Jackson uses Reflection or MethodHandles to assign the values:

person.setName("Sagar");
person.setAge(30);

7️⃣ Type conversion

If the field type doesn’t directly match (e.g., JSON "30" string to int), Jackson automatically performs type coercion using DeserializationFeature rules.

Example:

{ "age": "30" }  // string → int

Still maps correctly, because Jackson handles type conversion.


8️⃣ Return the populated object

Once all fields are processed and the END_OBJECT token is read, Jackson returns the fully constructed and populated Person object.

return person;

🧠 In short, internally:

  1. Tokenize JSON text
  2. Identify class metadata via Reflection
  3. Create object instance
  4. Map JSON fields → Java fields
  5. Type convert if needed
  6. Return populated object

🧩 Bonus: Reverse process — writeValueAsString(person)

When you serialize:

String json = mapper.writeValueAsString(person);

Jackson:

  1. Uses Reflection to inspect getters.
  2. Converts them into key-value pairs.
  3. Writes them out as a JSON string using a JsonGenerator.

🔬 Internals summary

StepInternal ComponentDescription
ParsingJsonParserReads raw JSON as tokens
MappingBeanDeserializerMaps tokens to Java fields
ReflectionJavaType, AnnotatedClassReads field/method metadata
Object creationConstructor / UnsafeCreates object instance
ConversionDeserializationContextHandles type coercion
OutputReturns fully hydrated object

💡 Interview Tip

If they ask:

“How does Jackson convert JSON to Java objects internally?”

Answer (summary version):

Jackson uses a streaming parser (JsonParser) to read JSON into tokens, then uses reflection-based deserializers (BeanDeserializer) to create an instance of the target class. It matches JSON fields to Java properties, sets values using reflection, performs type conversion when needed, and finally returns the populated object.

Published on: Oct 05, 2025, 11:13 PM  
 

Comments

Add your comment