Working with JSON in Java - potatoscript/json GitHub Wiki

β˜•οΈ Working with JSON in Java: Master JSON Like a Pro! 🎯

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! πŸš€πŸ“š


🎯 What is JSON in Java?

  • 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)

πŸ”₯ 1. Using Jackson Library for JSON in Java

Jackson is the most popular and powerful library for handling JSON in Java. To use Jackson:


πŸ“₯ Step 1: Add Jackson Dependency

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'

πŸ“ Step 2: Import Required Packages

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;

πŸ“© 2. Convert JSON to Java Object (Deserialization)

To convert a JSON string to a Java object, use ObjectMapper.readValue().


🎯 Example: Parse JSON String to Java Object

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 a User object.
  • The User class has matching fields with JSON keys.

πŸ“€ 3. Convert Java Object to JSON (Serialization)

To convert a Java object to a JSON string, use ObjectMapper.writeValueAsString().


🎯 Example: Convert Java Object to JSON

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.

πŸ“š 4. Working with JSON Files in Java

πŸ“₯ a) Reading JSON from a File

To read JSON from a file and convert it to a Java object:

User user = mapper.readValue(new File("data.json"), User.class);

🎯 Example: Read JSON from a File

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.

πŸ“€ b) Writing JSON to a File

To write a Java object to a JSON file:

mapper.writeValue(new File("data.json"), user);

🎯 Example: Write JSON to File

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.

🧩 5. Working with Nested JSON in Java

When JSON contains nested objects or arrays, you can map them using nested Java classes.


🎯 Example: Handling Nested JSON

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.

πŸ“‘ 6. Using JSON in REST APIs with Java

JSON is commonly used in APIs for request and response data.


🎯 Example: Sending JSON with HttpURLConnection

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.

🧠 7. Error Handling in JSON Parsing

When working with JSON, always handle parsing errors gracefully.


🎯 Example: Handling JSON Errors

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.

🧠 8. Gson: Alternative Library to Work with JSON in Java

If you prefer Google’s Gson for handling JSON, add the dependency:


πŸ“₯ Add Gson to Your Project

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.9.0</version>
</dependency>

🎯 Gson Example: Converting JSON to Java Object

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.

⚠️ **GitHub.com Fallback** ⚠️