Problem description

If the returned Json data has incomplete fields in an entity class, can Gson do entity mapping for us?

The problem the

We serialize a User entity to get Json data

{
	"userid": "1"."username": "Zhang SAN's nickname"."password": "123456"."gender": "Male"."realName": "Zhang"."email": "[email protected]"."phone": "1234567890"."headPic": "head pic"."country_code": "86"
}
Copy the code
  • The little knowledge

    Gson ignores null values during serialization, meaning that if there is no assignment, the field will not appear in JSON. If you want to preserve the field and null values, Gson can help you (as described in a later article).

For now we just need to know that serialization ignores NULL, as shown in the figure

The userID has disappeared because the value is null

{
	"username": "Zhang SAN's nickname"."password": "123456"."gender": "Male"."realName": "Zhang"."email": "[email protected]"."phone": "1234567890"."headPic": "head pic"."country_code": "86"
}
Copy the code

Deserialize the following JSON:

Userid, password, gender and headPic have been deleted

{
	"username": "Zhang SAN's nickname"."realName": "Zhang"."email": "[email protected]"."phone": "1234567890"."country_code": "86"
}
Copy the code

""

The problem summary

  1. When entities convert JSON, null values generally do not appear in the JSON string
  2. When converting an entity using JSON, even if the corresponding entity field is missing, it can be mapped to the entity, but the null value is replaced by the default value of the corresponding entity field type

Jumping pit communication

  1. In the use ofkotlinLanguage andJavaDifferent, Kotlin must initialize the value for the field or uselateinit varDelayed initialization. butlateinit varCan’t have default initialvalues, so in Kotlin the above problems will change, and entity classes will notlateinit varMust be initialized directly