Home > Software engineering >  How does the json returned from a model have a field name that does not exist in the domain object
How does the json returned from a model have a field name that does not exist in the domain object

Time:09-16

I am new to Spring and learning it from going over this guide on their website. https://spring.io/guides/tutorials/rest/

The section Supporting changes to the API where the name in the employee object is replaced with firstname and lastname. The json returned still has the field name although it's not part of the employee object anymore.

How come this property is called 'name' and how this property gets its "name"? I understand that getName() function inside Employee class is this property's value.

CodePudding user response:

The mapping mechanism that spring is using is based on the getters and Setters, so it is taken the name of the getter to create the field named "name" in the json even though it is not present in the employee object. Instead of using traditional reflection to introspect the object and return the fields and values, is using the getter/setter approach

As it is said in the tutorial:

  • Field name has been replaced by firstName and lastName.

  • A "virtual" getter for the old name property, getName() is defined. It uses the firstName and lastName fields to produce a value.

  • A "virtual" setter for the old name property is also defined, setName(). It parses an incoming string and stores it into the proper fields.

  • Related