Serialization of @ManyToOne object with customized child object in JPA/Jackson

jsonmanagedreference
jsonidentityinfo
jpa parent child relationship example
jackson objectmapper infinite recursion
many to many infinite recursion
jpa query child objects
org.codehaus.jackson.map.jsonmappingexception: infinite recursion (stackoverflowerror)
spring data jpa update child entity

I have two entity classes with bidirectional @OneToMany/@ManyToOne relationship. When I do serialize Class A, I don't want to have whole Class B inside class A, only the id field. But, class B still needs to appear as an object inside class A and not just a property. How can I achieve that? I am using JPA:2.2/Jackson:2.9.0

@Entity
public class A {

    private long id;

    @ManyToOne
    private B b;

    // ...
}

@Entity
public class B {

    private long id;
    private String str;
    private boolean bool;

    @OneToMany
    Set<A> aList;
    // ...
}

Desired result of Class A:

{
    "id" : 123;
    "b" : {
        "id" : 321;
    }
}

You can ignore Serialization on any object by using @JsonIgnore annotation example code should be :

@Entity
public class A {

    private long id;

    @ManyToOne
    private B b;

    // ...
}

@Entity
public class B {

    private long id;
    private String str;
    private boolean bool;

    @OneToMany
    @JsonIgnore
    Set<A> aList;
    // ...
}

Jackson, When we try to serialize an instance of “Item“, Jackson will throw a JsonMappingException exception: ? 1. 2. 3. 4. 5. 6. In our previous article, we have learned how to use the Jackson API for binding JSON data to Plain Old Java Object (POJO) and vice versa. In this article, I show you how to use the Jackson API to serialize and deserialize the java collection objects such as List, Set, and Map.

You can try use @JsonIgnoreProperties to ignore certain fields

@Entity
public class A {

    private long id;

    @ManyToOne
    private B b;

    // ...
}

@Entity
public class B {

    private long id;
    private String str;
    private boolean bool;

    @OneToMany
    @JsonIgnoreProperties({"ignoreField1", "ignoreField2"})
    Set<A> aList;
    // ...
}

How To Retrieve a Parent Field From a Child Entity in a One To , Here, the Book entity has a ManyToOne Annotation which is mapped by the authorId. Since getter methods are used to fetch objects, any getter method like the ones This is done to avoid an infinite recursion going on during serialization since Author Create a Jpa dao implementations for both entities  This quick tutorial will show how to serialize a Java entity with Jackson 2 using a Custom Serializer. If you want to dig deeper and learn other cool things you can do with the Jackson 2 – head on over to the main Jackson tutorial.

There are many ways to achieve this:

1) Ignore properties:

@Entity
public class A {

    private long id;

    @JsonIgnoreProperties({"prop1", "prop2"})
    @ManyToOne
    private B b;
}

2) JsonIdentityInfo and PropertyGenerator. Requires id property.

public class A {
   @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
   @JsonIdentityReference(alwaysAsId = true)
   public B b; 

   public long id;
}

3) JsonValue - indicates a single method/field that should be used to serialize the entire instance.

public class B {

    @JsonValue
    public long id;
}

4) Custom serializer:

@Entity
@JsonSerialize(using = ASerializer.class)
public class A {

    private long id;

    @ManyToOne
    private B b;

    // ...
}

You need to implement ASerializer in this case.

This is a not the easiest but flexible and a granular way of customisation of serialized objects.

See this example.

Three approachs to solve JSON recursive dependency , Using Jackson to serialize my JPA entities with many-to-many relationship into Before Jackson 2.0, handling of cyclic object graphs was limited to specific case of parent/child(bi-directional) references. i need the Approach #3 , i'am using @OneToMany & @ManyToOne annotations but it doesn't work. In these cases, you can instruct Jackson to deserialize the object to a Map. It will contain field names as keys and their deserialized contents as values. Note that the default deserializers apply for basic field types in the Map. Jackson deserializes the date as a collection, same as the array of hobbies.

JSON Bidirectional Relationship Support, Or if you're a Java developer who uses Jackson library, you may have Alternatively, one can develop custom serialization code that ignore any such is a parent object that has children (which it references) and those child objects, in turn, If you try to convert the above parent object to JSON (for example, by using the  A has a many to many relationship with both B and C, while B and C have a many to many relationship with each other. This creates a cycle from A -> B -> C -> A. Each object has a JsonIdentity annotation. Now when I go to serialize A where it is linked to B and C and B and C are linked to each … Read more »

Keenformatics: How To Solve JSON infinite recursion Stackoverflow , Coding in Spring 3 with JPA and Jackson is supposed to semplify your BeanSerializer.serialize(BeanSerializer.java:143) at is @JsonIdentityInfo: using it, everytime Jackson serializes your object, But in my case I also need the parent Id in the the child json as child @ManyToOne(fetch = FetchType. Jackson library provides a @JsonPropertyOrder annotation to specify the order of properties on serialization. Dependencies Let’s first add the following dependencies to the pom.xml:

How to get json response only with an id of the related entity , This will result in accessing only the serialized object and its name properties and requires Many-to-One relation with the Project entity. <artifactId>spring-​boot-starter-data-jpa</artifactId> The @OnDelete annotation allows removing all child records (tasks) import com.fasterxml.jackson.databind. Introduction. As already explained, the hibernate-types open-source project allows you to map JSON, ARRAY when using JPA and Hibernate.. Since I launched this project, one of the most wanted feature was to add support for customizing the underlying Jackson ObjectMappper, and since version 2.1.1, this can be done either declaratively or programmatically.

Comments
  • did u tried using @JsonIgnore annotation? or u can simply remove A object inside B it will still have ManyToOne relation
  • @Mustahsan I want to be able to fetch/serialize Class B independently. Adding @JsonIgnore will be problematic because then I will never access those fields inside the object.(?) Json structure should be presented as in the question
  • add @JsonIgnore before A's object
  • Right, but then I will not get "b" : { "id" : 321; } inside Class A, right?
  • you will get it inside A i am asking to add annotation before Declaration of object of A in class B before OneToMany
  • Hi @J-Alex , i have a few questions about option 2 and 3. Option 1 is no usefull because object has a lots of properties (more than 50). I did use option 2 in class B. Used @JsonIdentityInfo in class level in Class B but it resulted the field I wanted in Class A was just a field and not a nested object. About option 3, if I use @JsonValue on id field in Class B, does this mean that when I serialize Class B independent from Class A, still gonna get the whole object? Or just id in every case?
  • I tried to implement option 4 as well. I have a Set<Element> mySet = ... in my Class A and they have bidirectional (onetomany(Class A)/manytoone(Element)) relationship. When I serialize Class A, I get recursive problem. Any way to avoid it in my ASerializer class?
  • @Yonetmen in 3rd case it affects all serialization methods, independent serialization as well.
  • @Yonetmen regarding infinite recursion: stackoverflow.com/questions/45362300/… and stackoverflow.com/questions/54217220/…