⬅ Previous Next ➡

JSON, XML & APIs in Java

JSON, XML & APIs in Java: Gson/Jackson Parsing, XML Parsing, HttpClient API Calls & JSON Processing
  • JSON (JavaScript Object Notation) is a lightweight format for data exchange (key-value).
  • XML (eXtensible Markup Language) is a markup format used to store/transport structured data using tags.
  • In Java, JSON is commonly parsed using Gson or Jackson.
  • API calls can be done using HttpClient (Java 11+) and responses can be processed as JSON.

1) Handling JSON in Java (Basics)

  • JSON Example:
    • {"name":"Sourav","course":"Java","marks":88}
  • Two common ways to parse JSON:
    • Object Mapping (JSON ↔ Java Class)
    • Tree Model (read JSON nodes/keys)

2) Parsing JSON using Gson

  • Gson is simple for JSON to object conversion.
  • Main class: com.google.gson.Gson
// Gson Example (JSON -> Object and Object -> JSON)
import com.google.gson.Gson;

class Student {
    String name;
    String course;
    int marks;
}

class GsonDemo {
    public static void main(String[] args) {
        Gson gson = new Gson();

        String json = "{"name":"Sourav","course":"Java","marks":88}";

        // JSON -> Object
        Student s = gson.fromJson(json, Student.class);
        System.out.println(s.name + " " + s.course + " " + s.marks);

        // Object -> JSON
        s.marks = 95;
        String out = gson.toJson(s);
        System.out.println(out);
    }
}

3) Parsing JSON using Jackson (ObjectMapper)

  • Jackson is powerful and widely used for JSON processing.
  • Main class: com.fasterxml.jackson.databind.ObjectMapper
// Jackson Example (JSON -> Object and Object -> JSON)
import com.fasterxml.jackson.databind.ObjectMapper;

class Student2 {
    public String name;
    public String course;
    public int marks;
}

class JacksonDemo {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        String json = "{"name":"Sourav","course":"Java","marks":88}";

        // JSON -> Object
        Student2 s = mapper.readValue(json, Student2.class);
        System.out.println(s.name + " " + s.course + " " + s.marks);

        // Object -> JSON
        s.marks = 91;
        String out = mapper.writeValueAsString(s);
        System.out.println(out);
    }
}

4) Jackson Tree Model (JsonNode)

  • Useful when you do not have a fixed class structure.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

class JacksonTreeDemo {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        String json = "{"name":"Sourav","course":"Java","marks":88}";
        JsonNode node = mapper.readTree(json);

        System.out.println(node.get("name").asText());
        System.out.println(node.get("marks").asInt());
    }
}

5) Handling XML in Java (Basics)

  • Common XML parsing methods:
    • DOM Parser (loads whole XML in memory)
    • SAX Parser (event-based, faster for large XML)
  • DOM is easier for beginners.

6) XML Parsing using DOM Parser

  • Classes: DocumentBuilderFactory, DocumentBuilder, Document
// DOM XML Parse Example
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;

class XmlDomDemo {
    public static void main(String[] args) {
        try {
            // Example XML:
            // <student><name>Sourav</name><marks>88</marks></student>

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();

            // If file: db.parse(new File("student.xml"));
            // Here just show structure concept
            System.out.println("DOM parser reads tags and values from XML.");

        } catch (Exception e) {
            System.out.println("XML error: " + e.getMessage());
        }
    }
}

7) API Calls with HttpClient (Java 11+)

  • HttpClient supports GET/POST requests.
  • Main classes: HttpClient, HttpRequest, HttpResponse.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

class ApiGetDemo {
    public static void main(String[] args) {
        try {
            HttpClient client = HttpClient.newHttpClient();

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://api.github.com"))
                    .GET()
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            System.out.println("Status: " + response.statusCode());
            System.out.println("Body: " + response.body());

        } catch (Exception e) {
            System.out.println("API error: " + e.getMessage());
        }
    }
}

8) JSON Response Processing (HttpClient + Jackson)

  • Get API response as String and parse using Gson/Jackson.
import java.net.URI;
import java.net.http.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

class ApiJsonProcessDemo {
    public static void main(String[] args) {
        try {
            HttpClient client = HttpClient.newHttpClient();

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://api.github.com"))
                    .GET()
                    .build();

            HttpResponse<String> res = client.send(request, HttpResponse.BodyHandlers.ofString());

            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readTree(res.body());

            // Example: read one field if exists
            if (node.has("current_user_url")) {
                System.out.println("current_user_url: " + node.get("current_user_url").asText());
            } else {
                System.out.println("Key not found in response");
            }

        } catch (Exception e) {
            System.out.println("Process error: " + e.getMessage());
        }
    }
}

9) Quick Notes

  • Use Gson for simple parsing and Jackson for advanced features.
  • Use HttpClient (Java 11+) for modern API calls.
  • Always handle exceptions and check HTTP status codes.
  • For real projects, store API URL and keys safely (config/env).
⬅ Previous Next ➡