User user = gson.fromJson(json, User.class);
JSON (JavaScript Object Notation) has become the lingua franca of data exchange in modern web services, configuration files, and NoSQL databases. If you're a Java developer, you've likely faced the question: Which JSON library should I use?
JSONArray hobbies = new JSONArray(); hobbies.put("reading"); hobbies.put("swimming"); obj.put("hobbies", hobbies); json library java
String jsonString = "\"name\":\"Eve\",\"age\":28"; JSONObject obj = new JSONObject(jsonString); String name = obj.getString("name"); int age = obj.getInt("age"); JSON-B (JSR 367) is part of Jakarta EE. It provides a standard API similar to JAXB for XML. If you're working in a full Jakarta EE environment or prefer a vendor-neutral approach, this is your choice. Implementation JSON-B is just a specification. You need an implementation like Eclipse Yasson or Apache Johnzon . Maven Dependencies <!-- API --> <dependency> <groupId>jakarta.json.bind</groupId> <artifactId>jakarta.json.bind-api</artifactId> <version>3.0.0</version> </dependency> <!-- Implementation (Yasson) --> <dependency> <groupId>org.eclipse</groupId> <artifactId>yasson</artifactId> <version>3.0.3</version> </dependency> <!-- Also needs JSON-P for parsing --> <dependency> <groupId>jakarta.json</groupId> <artifactId>jakarta.json-api</artifactId> <version>2.1.1</version> </dependency> Basic Examples import jakarta.json.bind.Jsonb; import jakarta.json.bind.JsonbBuilder; Jsonb jsonb = JsonbBuilder.create();
// Deserialize User result = jsonb.fromJson(json, User.class); | Library | Serialization Speed | Deserialization Speed | Memory Usage | |---------|--------------------|----------------------|---------------| | Jackson | Fastest | Fastest | Moderate | | Gson | Fast | Fast | Low | | JSON-java | Slow | Slow | High (creates many objects) | | JSON-B (Yasson) | Moderate | Moderate | Moderate | User user = gson
Java lacks built-in JSON support in its standard library (until very recently, with JSON Binding in Jakarta EE). Fortunately, the ecosystem offers several mature, high-performance options.
// Serialize User user = new User("Frank", 45); String json = jsonb.toJson(user); It provides a standard API similar to JAXB for XML
import com.google.gson.Gson; Gson gson = new Gson(); User user = new User("Charlie", 35); String json = gson.toJson(user);