System.out.println(obj.toString(2)); // pretty print with 2 spaces indent
JSONArray hobbies = new JSONArray(); hobbies.put("reading"); hobbies.put("swimming"); obj.put("hobbies", hobbies);
@JsonIgnoreProperties(ignoreUnknown = true) public class User // ... json library java
ObjectMapper mapper = new ObjectMapper(); User user = new User("Alice", 30); String json = mapper.writeValueAsString(user); System.out.println(json); // Output: "name":"Alice","age":30
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! System
String json = "\"name\":\"Bob\",\"age\":25"; User user = mapper.readValue(json, User.class); System.out.println(user.getName()); // Bob
User user = gson.fromJson(json, User.class); Did I miss your favorite library
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?