Working with JSON in Java - potatoscript/json GitHub Wiki
Welcome to the Magical World of JSON and Java! π§ββοΈβοΈ
JSON is widely used in Java applications for data exchange. Java provides various powerful libraries to handle JSON effortlessly! ππ
- JSON (JavaScript Object Notation): A lightweight data format for storing and exchanging information.
-
Java + JSON: Java offers multiple libraries like:
- π Jackson (Most Popular)
- π Gson (Googleβs Library)
- π org.json (Simple JSON Parsing)
Jackson is the most popular and powerful library for handling JSON in Java. To use Jackson:
Add the following in your pom.xml
(if using Maven):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.0</version>
</dependency>
β For Gradle:
implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.0'
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
To convert a JSON string to a Java object, use ObjectMapper.readValue()
.
import com.fasterxml.jackson.databind.ObjectMapper;
class User {
public String name;
public int age;
public String[] hobbies;
// Default constructor
public User() {}
// Getters and setters
public String getName() { return name; }
public int getAge() { return age; }
public String[] getHobbies() { return hobbies; }
}
public class JsonToJavaExample {
public static void main(String[] args) {
String json = "{\"name\":\"Lucy Berry\",\"age\":26,\"hobbies\":[\"coding\",\"reading\"]}";
ObjectMapper mapper = new ObjectMapper();
try {
// Convert JSON to Java object
User user = mapper.readValue(json, User.class);
System.out.println("Name: " + user.getName());
System.out.println("Age: " + user.getAge());
} catch (Exception e) {
e.printStackTrace();
}
}
}
β Explanation:
-
readValue()
parses the JSON string into aUser
object. - The
User
class has matching fields with JSON keys.
To convert a Java object to a JSON string, use ObjectMapper.writeValueAsString()
.
import com.fasterxml.jackson.databind.ObjectMapper;
class User {
public String name;
public int age;
public String[] hobbies;
// Constructor
public User(String name, int age, String[] hobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
}
public class JavaToJsonExample {
public static void main(String[] args) {
User user = new User("Lucy Berry", 26, new String[]{"coding", "reading"});
ObjectMapper mapper = new ObjectMapper();
try {
// Convert Java object to JSON string
String jsonString = mapper.writeValueAsString(user);
System.out.println("JSON Data: " + jsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
β Explanation:
-
writeValueAsString()
converts a Java object into a JSON string.
To read JSON from a file and convert it to a Java object:
User user = mapper.readValue(new File("data.json"), User.class);
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
class User {
public String name;
public int age;
public String[] hobbies;
// Getters and setters
public String getName() { return name; }
public int getAge() { return age; }
}
public class ReadJsonFileExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
// Read JSON from file and convert to Java object
User user = mapper.readValue(new File("user_data.json"), User.class);
System.out.println("User Name: " + user.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
β Explanation:
-
mapper.readValue()
reads the JSON file and converts it to a Java object.
To write a Java object to a JSON file:
mapper.writeValue(new File("data.json"), user);
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
class User {
public String name;
public int age;
public String[] hobbies;
public User(String name, int age, String[] hobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
}
public class WriteJsonFileExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
User user = new User("Lucy Berry", 26, new String[]{"coding", "reading"});
try {
// Write Java object to JSON file
mapper.writeValue(new File("user_data.json"), user);
System.out.println("Data successfully written to file!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
β Explanation:
-
mapper.writeValue()
writes JSON to a file. - The file
user_data.json
contains formatted JSON.
When JSON contains nested objects or arrays, you can map them using nested Java classes.
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
// Address Class
class Address {
public String street;
public String city;
}
// User Class
class User {
public String name;
public int age;
public Address address;
}
public class NestedJsonExample {
public static void main(String[] args) {
String nestedJson = """
{
"name": "Lucy Berry",
"age": 26,
"address": {
"street": "123 Snoopy Lane",
"city": "Fukuoka"
}
}
""";
ObjectMapper mapper = new ObjectMapper();
try {
User user = mapper.readValue(nestedJson, User.class);
System.out.println("Street: " + user.address.street);
System.out.println("City: " + user.address.city);
} catch (IOException e) {
e.printStackTrace();
}
}
}
β Explanation:
- JSON with nested objects is mapped to nested Java classes.
JSON is commonly used in APIs for request and response data.
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class JsonApiExample {
public static void main(String[] args) {
try {
URL url = new URL("https://api.example.com/users");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set HTTP method and headers
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
// JSON data
String jsonInputString = """
{
"name": "Lucy Berry",
"age": 26
}
""";
// Send JSON data
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
System.out.println("Response Code: " + conn.getResponseCode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
β Explanation:
-
HttpURLConnection
sends JSON data via POST. - Set content type as
application/json
.
When working with JSON, always handle parsing errors gracefully.
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
class User {
public String name;
public int age;
}
public class JsonErrorHandling {
public static void main(String[] args) {
String invalidJson = "{\"name\":\"Lucy Berry\",\"age\":26,}"; // Invalid JSON
ObjectMapper mapper = new ObjectMapper();
try {
User user = mapper.readValue(invalidJson, User.class);
} catch (JsonProcessingException e) {
System.err.println("Error parsing JSON: " + e.getMessage());
}
}
}
β Explanation:
-
JsonProcessingException
handles errors during JSON parsing.
If you prefer Googleβs Gson for handling JSON, add the dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.0</version>
</dependency>
import com.google.gson.Gson;
class User {
public String name;
public int age;
}
public class GsonExample {
public static void main(String[] args) {
String json = "{\"name\":\"Lucy Berry\",\"age\":26}";
Gson gson = new Gson();
User user = gson.fromJson(json, User.class);
System.out.println("Name: " + user.name);
System.out.println("Age: " + user.age);
}
}
β Explanation:
-
gson.fromJson()
parses JSON into a Java object. -
gson.toJson()
converts Java objects into JSON.