Java Gson Lib
[ Java Common Libraries](#)\n\n* * *\n\nGson is a Java library provided by Google for converting Java objects to JSON representation (serialization) and converting JSON strings to Java objects (deserialization).\n\nThe main features of Gson include:\n\n* Simple and easy-to-use API\n* No annotations required in Java classes (but annotations are supported)\n* High performance\n* Support for generics\n* Support for custom serialization and deserialization\n\n**Core Classes:**\n\n* `Gson`: The main class, providing serialization and deserialization methods\n\n* `JsonElement`: Abstract class for JSON elements\n\n* `JsonObject`: JSON object representation\n* `JsonArray`: JSON array representation\n\n* * *\n\n## Why Use Gson?\n\nIn Java development, we often need to handle JSON data in the following scenarios:\n\n* Interacting with RESTful APIs\n* Configuration file reading and writing\n* Data persistence\n* Data exchange between different systems\n\nGson provides a simple and efficient way to accomplish these tasks, making it more convenient compared to Java's native JSON processing methods.\n\n* * *\n\n## Basic Usage of Gson\n\n### Adding Gson Dependency\n\nFirst, you need to add the Gson dependency to your project. If you use Maven, you can add it to your pom.xml:\n\ncom.google.code.gson\n\ngson\n\n2.8.9\n\nA simple example, converting between Java and JSON objects:\n\n## Example\n\nimport com.google.gson.Gson;\n\npublic class GsonDemo {\n\npublic static void main(String[] args){\n\n Gson gson =new Gson();\n\n// Java object to JSON\n\n Person person =new Person("Zhang San", 30);\n\nString json = gson.toJson(person);\n\nSystem.out.println(json);// Output: {"name":"Zhang San","age":30}\n\n// JSON to Java object\n\n Person parsedPerson = gson.fromJson(json, Person.class);\n\nSystem.out.println(parsedPerson.getName());// Output: Zhang San\n\n}\n\n}\n\nclass Person {\n\nprivate String name;\n\nprivate int age;\n\n// Constructor\n\npublic Person(String name, int age){\n\nthis.name= name;\n\nthis.age= age;\n\n}\n\n// getter methods (Gson needs getter/setter)\n\npublic String getName(){return name;}\n\npublic int getAge(){return age;}\n\n}\n\n### Creating a Gson Instance\n\nGson gson =new Gson();\n\n### Java Object to JSON (Serialization)\n\n## Example\n\nclass User {\n\nprivate String name;\n\nprivate int age;\n\n// Constructor, getter and setter omitted\n\n}\n\nUser user =new User("Zhang San", 25);\n\nString json = gson.toJson(user);\n\n// Output: {"name":"Zhang San","age":25}\n\n### JSON to Java Object (Deserialization)\n\n## Example\n\nString json ="{"name":"Li Si","age":30}";\n\n User user = gson.fromJson(json, User.class);\n\nSystem.out.println(user.getName());// Output: Li Si\n\n### Common Features\n\n**Collection Handling**\n\n## Example\n\n// Serialize collection\n\n List people =Arrays.asList(\n\nnew Person("Wang Wu", 28),\n\nnew Person("Zhao Liu", 32)\n\n);\n\nString jsonList = gson.toJson(people);\n\n// Deserialize collection\n\n Type listType =new TypeToken<List>(){}.getType();\n\n List parsedPeople = gson.fromJson(jsonList, listType);\n\n**Date Handling**\n\n## Example\n\nGson gson =new GsonBuilder()\n\n .setDateFormat("yyyy-MM-dd HH:mm:ss")\n\n .create();\n\nDate now =new Date();\n\nString dateJson = gson.toJson(now);\n\nDate parsedDate = gson.fromJson(dateJson, Date.class);\n\n**Tree Model Handling**\n\n## Example\n\nString json ="{"name":"Li Si","age":25}";\n\n JsonElement element = JsonParser.parseString(json);\n\n JsonObject object = element.getAsJsonObject();\n\nString name = object.get("name").getAsString();\n\nint age = object.get("age").getAsInt();\n\n### Common Configurations\n\n**Pretty Printing**\n\nGson gson = new GsonBuilder() .setPrettyPrinting() .create();\n**Null Value Handling**\n\nGson gson = new GsonBuilder() .serializeNulls() // Serialize null values .create();\n**Field Naming Policy**\n\nGson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create();// Converts userName to user_name\n\n* * *\n\n## Advanced Features of Gson\n\n### Handling Complex Objects\n\nGson can handle complex data structures including nested objects, arrays, collections, etc.:\n\n## Example\n\nclass Order {\n\nprivate String orderId;\n\nprivate List products;\n\n// Other code omitted\n\n}\n\nOrder order =new Order("123", Arrays.asList(\n\nnew Product("mobile phone", 1, 2999.00),\n\nnew Product("headphones", 2, 199.00)\n\n));\n\nString json = gson.toJson(order);\n\n### Using TypeToken to Handle Generics\n\nWhen you need to handle generic collections, you can use TypeToken:\n\n## Example\n\nString json ="[{"name":"apple","price":5.5},{"name":"banana","price":3.2}]";\n\nType productListType =new TypeToken<List>(){}.getType();\n\n List products = gson.fromJson(json, productListType);\n\n### Custom Serialization and Deserialization\n\nYou can customize processing logic by implementing the JsonSerializer and JsonDeserializer interfaces:\n\n## Example\n\npublic class DateSerializer implements JsonSerializer{\n\nprivate static final SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd");\n\n@Override\n\npublic JsonElement serialize(Date date, Type type, JsonSerializationContext context){\n\nreturn new JsonPrimitive(format.format(date));\n\n}\n\n}\n\n// Using custom serializer\n\n Gson gson =new GsonBuilder()\n\n .registerTypeAdapter(Date.class, new DateSerializer())\n\n .create();\n\n### Using Annotations\n\nGson provides some useful annotations:\n\n## Example\n\nclass User {\n\n @SerializedName("user_name")// JSON field name\n\nprivate String name;\n\n@Expose(serialize =false)// Not participating in serialization\n\nprivate String password;\n\n@Since(1.0)// Version control\n\nprivate String email;\n\n}\n\n* * *\n\n## GsonBuilder Configuration\n\nGsonBuilder provides various configuration options:\n\n## Example\n\nGson gson =new GsonBuilder()\n\n .setPrettyPrinting()// Pretty printing\n\n .serializeNulls()// Serialize null values\n\n .setDateFormat("yyyy-MM-dd")// Date format\n\n .disableHtmlEscaping()// Disable HTML escaping\n\n .create();\n\n* * *\n\n## Performance Considerations\n\n* Reuse Gson instances: Gson is thread-safe, it is recommended to reuse rather than frequently create new instances\n* For large amounts of data processing, consider using the streaming API (JsonReader/JsonWriter)\n* Complex object structures will affect performance\n\n* * *\n\n## Comparison of Gson with Other JSON Libraries\n\n| Feature | Gson | Jackson | org.json |\n| --- | --- | --- | --- |\n| Ease of Use | High | Medium | High |\n| Performance | Medium | High | Low |\n| Feature Completeness | High | Very High | Low |\n| Community Support | High | Very High | Medium |\n\n* * *\n\n## Summary\n\nGson is a powerful and simple JSON processing library, suitable for most Java projects. It provides:\n\n* Simple API design\n* Flexible configuration options\n* Good performance\n* Rich functionality\n\nFor simple JSON processing needs, Gson is usually the first choice for Java developers. For high-performance requirements or complex scenarios, you can consider (#) and other libraries.\n\n[ Java Common Libraries](#)
YouTip