Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Data Exchange with JSON in AJAX and Java Servlets

Tech 1

Plain Text vs Structured Data in AJAX

Simple string responses are adequate for basic server outputs. However, retrieving complex structures such as object collections necessitates a structured data format.

let requester;
function retrieveData() {
  requester = new XMLHttpRequest();
  requester.open("GET", "/api/plain-text", true);
  requester.onreadystatechange = processResponse;
  requester.send();
}
function processResponse() {
  if (requester.readyState === 4 && requester.status === 200) {
    console.log(requester.responseText);
  }
}
@WebServlet("/api/plain-text")
public class PlainTextServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/plain;charset=UTF-8");
    resp.getWriter().write("Simple string payload");
  }
}

JSON as a Data Interchange Format

JSON (JavaScript Object Notation) is a lightweight, language-independent text format for representing structured data. It offers several advantages for web data exchange:

  • Lightweight nature focused purely on data serialization.
  • Seamless mapping between frontend JavaScript objects and backend models.
  • Native parsing capabilities in modern JavaScript engines.
  • Widespread adoption as the default format in modern AJAX implementations.

Differentiating JSON from JS Objects

JSON is essentially a string representation of a JavaScript object. While an object is a live data structure in memory, JSON is its textual serialization.

// JS Object Literal
let userObj = { username: "admin", accessLevel: 5 };

// JSON String
let userJson = '{"username": "admin", "accessLevel": 5}';

Conversion Between JSON and Objects

To deserialize a JSON string into a JavaScript object, apply the JSON.parse() method:

let parsedObj = JSON.parse('{"username": "admin", "accessLevel": 5}');
console.log(parsedObj.username);

To serialize a JavaScript object into a JSON string, utilize JSON.stringify():

let stringified = JSON.stringify({ username: "admin", accessLevel: 5 });
console.log(stringified);

Automating Serialization with Gson

Manually constructing JSON strings in Java is error-prone and difficult to maintain. The Gson library automates the conversion between Java objects and JSON.

Frontend implementation:

let asyncHttp;
function fetchUsers() {
  asyncHttp = new XMLHttpRequest();
  asyncHttp.open("GET", "/api/employee-list", true);
  asyncHttp.onreadystatechange = renderUsers;
  asyncHttp.send();
}
function renderUsers() {
  if (asyncHttp.readyState === 4 && asyncHttp.status === 200) {
    const payload = asyncHttp.responseText;
    const staff = JSON.parse(payload);
    for (let i = 0; i < staff.length; i++) {
      console.log(staff[i].fullName);
      console.log(staff[i].yearsExp);
    }
  }
}

Backend implementation (requires Gson dependency):

package com.example.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.example.model.Employee;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

@WebServlet("/api/employee-list")
public class EmployeeListServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Employee emp1 = new Employee("Alice", 3, "Engineering", new Date());
    Employee emp2 = new Employee("Bob", 5, "Marketing", new Date());

    ArrayList<Employee> roster = new ArrayList<>();
    roster.add(emp1);
    roster.add(emp2);

    resp.setContentType("application/;charset=UTF-8");
    GsonBuilder builder = new GsonBuilder().setDateFormat("yyyy-MM-dd");
    Gson gson = builder.create();
    String Output = gson.toJson(roster);

    resp.getWriter().print(Output);
  }
}
Tags: Ajax

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.