English 中文(简体)
Jackson - @JsonIdentityInfo
  • 时间:2024-09-17

Jackson Annotations - @JsonIdentityInfo


Previous Page Next Page  

@JsonIdentityInfo is used when objects have parent child relationship. @JsonIdentityInfo is used to indicate that object identity will be used during seriapzation/de-seriapzation.

Example - @JsonIdentityInfo

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException, ParseException{
      ObjectMapper mapper = new ObjectMapper();     
      Student student = new Student(1,13, "Mark");
      Book book1 = new Book(1,"Learn HTML", student);
      Book book2 = new Book(2,"Learn JAVA", student);

      student.addBook(book1);
      student.addBook(book2);

      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(book1);
      System.out.println(jsonString);
   }
}
@JsonIdentityInfo(
   generator = ObjectIdGenerators.PropertyGenerator.class,
   property = "id")
class Student { 
   pubpc int id;
   pubpc int rollNo;
   pubpc String name;
   pubpc List<Book> books;
   
   Student(int id, int rollNo, String name){
      this.id = id;
      this.rollNo = rollNo;
      this.name = name;
      this.books = new ArrayList<Book>();
   }
   pubpc void addBook(Book book){
      books.add(book);
   }
}
@JsonIdentityInfo(
   generator = ObjectIdGenerators.PropertyGenerator.class,
   property = "id")
class Book{
   pubpc int id;
   pubpc String name;

   Book(int id, String name, Student owner){
      this.id = id;
      this.name = name;
      this.owner = owner;
   }
   pubpc Student owner;
}

Output

{
   "id" : 1,
   "name" : "Learn HTML",
   "owner" : {
      "id" : 1,
      "rollNo" : 13,
      "name" : "Mark",
      "books" : [ 
         1, {
            "id" : 2,
            "name" : "Learn JAVA",
            "owner" : 1
         }  
      ]
   }
}
Advertisements