CodeBlanks Logo Icon CodeBlanks

writeValueAsString

Learn to convert objects to JSON with writeValueAsString.

Serialization with writeValueAsString

To convert a Java object to structured text, use mapper.writeValueAsString(obj). The returned String is in a structured format. A User u = new User("Ayşe", 30); instance serializes as {"name":"Ayşe","age":30}.

Fields become keys by default. To make the output pretty, use mapper.enable(SerializationFeature.INDENT_OUTPUT). To skip null values, add Jackson's null-skipping annotation on the class.

Formatting the output

Default output is single-line compact text. For readability, mapper.enable(SerializationFeature.INDENT_OUTPUT) gives indented output. To skip null fields, add Jackson's null-skipping annotation on the class.

For special types like dates, mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) is used. These settings are made on a single ObjectMapper instance and affect every serialization it does.

Practice Convert a User object to structured text

Define record User(String name, int age) {}. Add throws Exception to main. Create an ObjectMapper mapper = new ObjectMapper();, create a user with User u = new User("Mehmet", 25);, produce text with String text = mapper.writeValueAsString(u); and print it with System.out.println(text);.

Starter code

Main.java
import com.fasterxml.jackson.databind.ObjectMapper;

// Define the User record

public class Main {
    public static void main(String[] args) throws Exception {
        // ObjectMapper, User instance, writeValueAsString and println

    }
}

Sample solution

Main.java
import com.fasterxml.jackson.databind.ObjectMapper;

record User(String name, int age) {}

public class Main {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        User u = new User("Mehmet", 25);
        String text = mapper.writeValueAsString(u);
        System.out.println(text);
    }
}

Expected output

{"name":"Mehmet","age":25}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does writeValueAsString return?

  • byte[]
  • Object
  • List
  • String Correct answer

Explanation: writeValueAsString returns structured text as a String.

2 Complete the serialization call

Question
String text = mapper.____(u);
Answer
String text = mapper.writeValueAsString(u);

Explanation: writeValueAsString converts the User to structured text.

3 Match the serialization concepts

Term Meaning
writeValueAsString Object to text
INDENT_OUTPUT Indented output
@JsonInclude Skipping null values
User u = new User(...) Object to serialize

All lessons in Intermediate