Json Library: Java

System.out.println(obj.toString(2)); // pretty print with 2 spaces indent

Whichever library you choose, mastering JSON processing is essential for modern Java development. Now go convert those objects to JSON and back! Did I miss your favorite library? Let me know about JSON-smart, Moshi (from Square), or Boon in the comments below!

User user = gson.fromJson(json, User.class); json library java

// Serialize User user = new User("Frank", 45); String json = jsonb.toJson(user);

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. System

ObjectMapper mapper = new ObjectMapper(); User user = new User("Alice", 30); String json = mapper.writeValueAsString(user); System.out.println(json); // Output: "name":"Alice","age":30

JSONArray hobbies = new JSONArray(); hobbies.put("reading"); hobbies.put("swimming"); obj.put("hobbies", hobbies); Let me know about JSON-smart, Moshi (from Square),

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();