English 中文(简体)
Jackson - @JsonUnwrapped
  • 时间:2024-11-05

Jackson Annotations - @JsonUnwrapped


Previous Page Next Page  

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

Example - @JsonUnwrapped

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;

pubpc class JacksonTester {
   pubpc 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 {
   pubpc int id;   
   @JsonUnwrapped
   pubpc Name name;
   Student(int id, Name name){
      this.id = id;
      this.name = name;
   }
   static class Name {
      pubpc String first;
      pubpc String last;
   }
}

Output

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