Sobes.tech
Junior — Middle

Can you explain what Gson is and how it works with fields during serialization and deserialization?

sobes.tech AI

Answer from AI

Gson is a Java library for converting objects to JSON and back (serialization and deserialization).

How it works with fields:

  • By default, Gson serializes all object fields, including private ones.
  • During deserialization, Gson creates an object and fills the fields from JSON by name.
  • Annotations (@Expose, @SerializedName) can be used to control which fields are serialized and under what names.

Example:

class User {
  @SerializedName("user_name")
  private String name;
  private int age;
}

Gson gson = new Gson();
User user = new User("Ivan", 30);
String json = gson.toJson(user); // {"user_name":"Ivan","age":30}