β JSON with Java β Encode, Decode, and Work with JSON (2025 Guide)
π§² Introduction β Why Use JSON with Java?
JSON (JavaScript Object Notation) is a lightweight, human-readable format commonly used for data exchange between servers and clients. Java provides multiple libraries to work with JSON, allowing developers to parse, generate, and manipulate JSON data easily within REST APIs, desktop apps, or enterprise systems.
π― In this guide, youβll learn:
- The most popular JSON libraries in Java
- How to encode and decode JSON with real examples
- Using JSON in RESTful APIs
- Best practices and tips for error-free data handling
π Popular JSON Libraries in Java
| Library Name | Description |
|---|---|
org.json | Simple and minimalistic native implementation |
Jackson | Powerful, fast, supports POJO mapping |
Gson (by Google) | Lightweight, easy-to-use, great for Android |
JSON-B | Standardized API (Jakarta EE) |
β Working with JSON using org.json
π§ͺ Encode β Create JSON Object from Java Map
import org.json.JSONObject;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Object> user = new HashMap<>();
user.put("name", "Alice");
user.put("age", 30);
JSONObject json = new JSONObject(user);
System.out.println(json.toString());
}
}
π Output:
{"name":"Alice","age":30}
π§ͺ Decode β Parse JSON String to Java Object
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonString = "{\"name\":\"Bob\", \"age\":25}";
JSONObject obj = new JSONObject(jsonString);
String name = obj.getString("name");
int age = obj.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
}
}
π³ Using JSON with Jackson (POJO Mapping)
Jackson is ideal for converting between Java objects and JSON.
π§ͺ Encode β Object to JSON String
import com.fasterxml.jackson.databind.ObjectMapper;
class User {
public String name;
public int age;
User(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) throws Exception {
User user = new User("Carol", 22);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
System.out.println(json);
}
}
π§ͺ Decode β JSON String to Object
String jsonStr = "{\"name\":\"Dan\",\"age\":40}";
User user = mapper.readValue(jsonStr, User.class);
System.out.println(user.name + " is " + user.age + " years old.");
βοΈ Great for working with REST APIs and data models
βοΈ Automatically maps fields between JSON and Java objects
π‘ JSON in Java REST API (Spring Boot Example)
@RestController
public class UserController {
@PostMapping("/api/user")
public String receiveJson(@RequestBody User user) {
return "Received user: " + user.name;
}
@GetMapping("/api/user")
public User sendJson() {
return new User("Eva", 28);
}
}
βοΈ Spring Boot automatically handles JSON serialization/deserialization
βοΈ Uses Jackson under the hood
π οΈ Best Practices for JSON in Java
| Best Practice | Benefit |
|---|---|
Use @JsonProperty for custom names | Handles snake_case β camelCase conversions |
Always handle exceptions (try/catch) | Prevents crashes from malformed JSON |
| Validate JSON input | Ensures security and correct structure |
| Use POJOs for complex structures | Improves maintainability and readability |
π Summary β Recap & Next Steps
JSON is essential in modern Java development, especially for building APIs, mobile apps, and data services. Libraries like Jackson, Gson, and org.json make handling JSON easy and flexible.
π Key Takeaways:
- Use
org.jsonfor quick JSON parsing and generation - Use Jackson or Gson for working with POJOs and APIs
- Spring Boot auto-handles JSON in REST controllers
- Validate and format JSON for clean data communication
βοΈ Real-world use:
Used in REST APIs, Spring Boot apps, Android apps, enterprise systems, and web services.
β FAQ β JSON with Java
β Which Java library is best for JSON?
β
Jackson is the most powerful and commonly used for enterprise apps. Gson is great for lightweight or Android projects.
β Can I convert a JSON string to a Java object?
β
Yes. Use Jacksonβs ObjectMapper.readValue() or Gsonβs fromJson().
β How do I return JSON from a Java REST API?
β
Use Spring Bootβs @RestController with @RequestBody and @ResponseBody.
β Do I need to install org.json separately?
β
In some cases, yes. It may need to be added as a dependency if not bundled with your environment.
Share Now :
