Jackson Annotations - @JsonUnwrapped



Overview

@JsonUnwrapped annotation is used to unwrap values of objects during serialization or de-serialization.

Example - Serialization without using @JsonUnwrapped

JacksonTester.java

package com.tutorialspoint;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]) throws IOException, ParseException{
      ObjectMapper mapper = new ObjectMapper();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
      Date date = simpleDateFormat.parse("20-12-1984");
      Student.Name name = new Student.Name();
      name.first = "Jane";
      name.last = "Doe";
      Student student = new Student(1, name);
      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(student);
      System.out.println(jsonString);
   }
}
class Student {
   public int id;   
   public Name name;
   Student(int id, Name name){
      this.id = id;
      this.name = name;
   }
   static class Name {
      public String first;
      public String last;
   }
}

Output

Run the JacksonTester and verify the output −

{
  "id" : 1,
  "name" : {
    "first" : "Jane",
    "last" : "Doe"
  }
}

Example - Serialization with @JsonUnwrapped

JacksonTester.java

package com.tutorialspoint;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]) throws IOException, ParseException{
      ObjectMapper mapper = new ObjectMapper();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
      Date date = simpleDateFormat.parse("20-12-1984");
      Student.Name name = new Student.Name();
      name.first = "Jane";
      name.last = "Doe";
      Student student = new Student(1, name);
      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(student);
      System.out.println(jsonString);
   }
}
class Student {
   public int id;   
   @JsonUnwrapped
   public Name name;
   Student(int id, Name name){
      this.id = id;
      this.name = name;
   }
   static class Name {
      public String first;
      public String last;
   }
}

Output

Run the JacksonTester and verify the output −

{
  "id" : 1,
  "first" : "Jane",
  "last" : "Doe"
}

Here we can see, without using @JsonUnwrapped, Jackson is serializing the name object to a new JSON object whereas using @JsonUnwrapped annotation, we're able to unwrap name field and serialize them as other fields.

Advertisements