Search code examples
javarestjacksonresteasy

Jackson: How to Detect Modified Object after Deserialization and Serialization?


I have an object, any data object ( for example, Person) serialized and brought down to the user interface. Users click the save button with or without changes.

What is the best way to detect that the object has changed by the user while on the UI? Note that the object may have child records and changes on those records should also set a "need-to-save" property to true.

Before building our own logic, is there a standard way of doing this? Our client is Angular 1.6 and server site is Java 1.8 with RESTEASY. But I would imagine this to be a common problem for any platform that uses serialization.


Solution

  • The solution required both Server and Client site changes:

    1. It helps if your Entity objects inherit from one single object. In our system, all model objects inherit from a class called JsonModelObject. We introduced a boolean jsonDirty field, initialized to false. So automatically all serialized objects come down to the angular front end with this flag set as false.

    2. Client Site: It also helps all CRUD operations of your system call common methods. In our case, when a record is received from the server site, we use JSON.stringify and store it as a string, for example:
      $scope.editRecordForChangeCheck = JSON.stringify($scope.editRecord);

    3. When saving, we check both form's $dirty flag (if angular) and also compare the JSON.stringify of the record being saved with the initial $scope.editRecordForChangeCheck. Note that in case of angular, if there are fields that got changed programmatically the angular $dirty flag is not set to true.

      var isDirty = $scope.form.$dirty || ($scope.editRecordForChangeCheck !== JSON.stringify($scope.editChildRecord)); if (isDirty ) { $scope.editRecord.jsonDirty = true; // here you call your api... }