Issue with Jackson serialization in @ManyToMany association

I am currently facing the following scenario:

//--class user --
private ....

@OneToMany(targetEntity = UserRoles.class, mappedBy = "iduser", fetch = FetchType.LAZY)
@JsonManagedReference
private List<UserRoles> userRoleList = new ArrayList<>();

@OneToOne(targetEntity = Login.class, cascade = CascadeType.ALL)
@JoinColumn(name = "iduser", referencedColumnName = "iduser")
@JsonManagedReference
private Login login;

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "n_gruppi_user", joinColumns = { @JoinColumn(name = "iduser") }, inverseJoinColumns = {
        @JoinColumn(name = "idgruppo") })
@JsonManagedReference
List<Gruppi> groups = new ArrayList();

Following class:

@Entity
@Table(name = "gruppi")
@EntityListeners(AuditingEntityListener.class)

@Data
public class Gruppi implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long idgruppo;
private long iduser;
private String tipo;
private String nome_gruppo;
private String pass_gruppo;
private String email_gruppo;
private String descr_gruppo;
private Timestamp data_creazione;


@ManyToMany(mappedBy = "groups")
@JsonBackReference
List<User> users_group = new ArrayList<>();

When running the application, everything works fine and I receive https://i.stack.imgur.com/lain2.jpg However, when serializing my object of User, Jackson serializes everything except users_group due to the usage of @JsonBackReference. Yet, not using @JsonBackReference leads to circularity problems. How can I ensure that users_group is also serialized? Your help in this matter would be greatly appreciated!

Answer №1

In order to effectively manage both classes, it is essential to have a unique identifier property such as ID that can be used for object identification in the database. This identifier will assist Jackson in identifying instances at runtime. Instead of using @JsonBackReference and @JsonManagedReference, you can utilize the

com.fasterxml.jackson.annotation.JsonIdentityInfo
annotation:

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "iduser")
class User {
...
}

Additionally,

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "idgruppo")
class Gruppi {
...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying the autocomplete feature to showcase options in a dropdown menu

I have a form that requires country states to be displayed in a dropdown menu. Despite having autocomplete functionality, I am only able to see the response as an array in the console.log when searching for a specific state. I have tried to switch from aut ...

A step-by-step guide on accessing the data from an uploaded JSON file in a React application

One exciting feature is the drag and drop component that allows users to add multiple files. However, there seems to be an issue with displaying the content of a JSON file once it's added. Below is the code snippet in question: if (files?.length) ...

The application appears to be overloaded with tasks on its main thread, potentially causing errors

I am currently in the process of developing an app for user login and registration. The app relies on receiving a JSON response from a webservice to interact with the database. However, during the registration process, I encountered the following error mes ...

Having trouble interpreting JSON attribute "null"

I encountered a problem while attempting to parse a JSON "null" property. Can someone help me understand what the issue might be? The JSON I used was as follows: { "properties" : { "null" : { "value" : false } } } I validated th ...

Using the Requests library: How to send true or false values in the parameters

Here's a snippet of code I've been working on that involves sending a request to an API: request_parameters = { "headers": myheaders, "params": { "myparam": True } } response = requests.get(myurl, ** ...

Decoding PHP Webservice Output on Android

I am currently working on consuming a PHP Web service using JSON in an Android app. After making a request to the server, I received the following response data: string(170) "["14","Samsung","1","15","Nokia","1","16","Sony Ericson","1","18","LG","1","19" ...

Is there a way to update a JSON Array in PHP by replacing the existing data with the new data?

I am working with a JSON file and have encountered an issue when trying to delete an object. Whenever I create a new array and write it back to the original JSON file, the new data ends up overwriting the entire file. I have tried using functions like arr ...

Unexpected error: The 'try!' expression has caused a fatal error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "hours", intValue: nil)

I encountered a strange error that I am unable to comprehend. The issue arose only after adding a new item. Here is the error message: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(CodingKeys(stri ...

Distinguishing between native and custom error objects: a comprehensive guide

When working with errors in my node app, I find it challenging to handle both custom and native errors seamlessly. Errors are not just ordinary JavaScript objects, which adds complexity to error handling. To manage custom errors, I am experimenting with t ...

trouble encountered while parsing JSON information using JavaScript

[ [ { "Id": 1234, "PersonId": 1, "Message": "hiii", "Image": "5_201309091104109.jpg", "Likes": 7, "Status": 1, "OtherId": 3, "Friends": 0 } ], [ { "Id": 201309091100159, "PersonI ...

Condition in Bash script for verifying JSON response

This particular script is designed to notify me whenever there is an error response. Problem: Even when the execution is successful, I am still receiving an email. Bash script: #!/bin/bash DATA=$(wget --timeout 5 -O - -q -t 1 http://this.url/?parm=1&bs ...

Issue with unnamed column in Pandas dataframe prevents insertion into MySQL from JSON data

Currently, I am working with a large JSON file and attempting to dynamically push its data into a MySQL database. Due to the size of the JSON file, I am parsing it line by line in Python using the yield function, converting each line into small pandas Data ...

get value from json with specified key

Here is a function that handles the success of my AJAX call: success: function(responseJson) { var receivedData = []; $.each(responseJson.jsonArray, function(index) { $.each(responseJson.jsonArray[index], function(key, value) ...

AngularJS utilizes a nested ng-repeat for displaying folder structures in the user interface

I am facing a challenge where I need to generate a comprehensive list of files and folders from a JSON object. The folder structure can be quite intricate, with the potential for multiple nested levels. In my specific example, I have only included up to th ...

The request method 'PUT' is not currently supported

Currently, I am working on a project that involves springboot, angularjs, and restful services. Here is my REST controller: @RequestMapping(value="/updatestructure/{ch}", method = RequestMethod.PUT) public @ResponseBody Structurenotification updateStruct ...

Getting Ajax response in HTML Unit can be achieved by leveraging its capability to render the HTML content of the web page

My web application responds with JSON data when I make AJAX requests to the server for CRUD operations. This is because I utilize jQuery to handle the data without needing to refresh the page (MVC). When a new entry is created in the system, the server sen ...

Transform legitimate JSON into a Task<string>

Currently, I am working on mocking ReadAsStringAsync on the first line to be used in a unit test that will result in a Task where the string represents the JSON provided below: var jsonString = await response.Content.ReadAsStringAsync(); // converting it ...

Which is the better choice: JSON file or SQL for storing data?

I am in the process of developing a website that will feature an ajax search functionality. This search will retrieve data either from a JSON file or from a MySQL database. I am unsure which technology would be best suited to store this data. With approxim ...

Interested in learning how to extract an array from a description in Swift 4?

Currently delving into Swift 4, I've come across an algorithm that generates the base 64 representation of an array, as shown below: extension String { func fromBase64() -> String? { guard let data = Data(base64Encoded: self) else { ...

Error encountered during Rails JSON conversion operation

I recently encountered an unusual error while attempting to convert my object to JSON for an API connection. Here is a detailed account of my experience. Upon calling JSON.generate(self) The resulting output was: {"validation_context":null,"errors":{}, ...