5/24/2026

Efficient JSON serialization with Jackson and Java

 



📌 Introduction



JSON serialization is a fundamental part of modern Java applications — converting Java objects into JSON and back. Jackson is the most widely used library for this purpose in the Java ecosystem, offering powerful, flexible, and performant serialization mechanisms.

In this article, we'll explore:

  • Basic Jackson setup
  • Custom serialization & deserialization
  • A real-world one-to-many example: CarDTOCarAttributeDTO

📚 References:


⚙️ 1. Maven Dependency

Add Jackson to your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.17.0</version>
</dependency>

🏗️ 2. Define the DTOs

CarAttributeDTO — The "Many" Side

public class CarAttributeDTO {

    private String attributeName;   // e.g. "color", "engine", "transmission"
    private String attributeValue;  // e.g. "red", "V8", "automatic"

    // Constructors
    public CarAttributeDTO() {}

    public CarAttributeDTO(String attributeName, String attributeValue) {
        this.attributeName = attributeName;
        this.attributeValue = attributeValue;
    }

    // Getters & Setters
    public String getAttributeName() { return attributeName; }
    public void setAttributeName(String attributeName) { 
        this.attributeName = attributeName; 
    }

    public String getAttributeValue() { return attributeValue; }
    public void setAttributeValue(String attributeValue) { 
        this.attributeValue = attributeValue; 
    }
}

CarDTO — The "One" Side (with One-to-Many relationship)

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.List;

@JsonInclude(JsonInclude.Include.NON_NULL) // Excludes null fields from JSON
public class CarDTO {

    @JsonProperty("car_id")
    private Long id;

    @JsonProperty("brand")
    private String brand;           // e.g. "BMW"

    @JsonProperty("model")
    private String model;           // e.g. "M3"

    @JsonProperty("year")
    private int year;               // e.g. 2024

    @JsonProperty("attributes")
    private List<CarAttributeDTO> attributes; // One-to-Many

    // Constructors
    public CarDTO() {}

    public CarDTO(Long id, String brand, String model, 
                  int year, List<CarAttributeDTO> attributes) {
        this.id = id;
        this.brand = brand;
        this.model = model;
        this.year = year;
        this.attributes = attributes;
    }

    // Getters & Setters
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getBrand() { return brand; }
    public void setBrand(String brand) { this.brand = brand; }

    public String getModel() { return model; }
    public void setModel(String model) { this.model = model; }

    public int getYear() { return year; }
    public void setYear(int year) { this.year = year; }

    public List<CarAttributeDTO> getAttributes() { return attributes; }
    public void setAttributes(List<CarAttributeDTO> attributes) { 
        this.attributes = attributes; 
    }
}

🔄 3. Basic Serialization (Object → JSON)

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.util.List;

public class JacksonSerializationExample {

    public static void main(String[] args) throws Exception {

        // Build the CarDTO with attributes (One-to-Many)
        List<CarAttributeDTO> attributes = List.of(
            new CarAttributeDTO("color",        "Frozen Black"),
            new CarAttributeDTO("engine",       "3.0L TwinPower Turbo"),
            new CarAttributeDTO("transmission", "8-Speed Automatic"),
            new CarAttributeDTO("horsepower",   "503 HP")
        );

        CarDTO car = new CarDTO(1L, "BMW", "M3 Competition", 2024, attributes);

        // Configure ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT); // Pretty print

        // Serialize to JSON String
        String json = mapper.writeValueAsString(car);
        System.out.println(json);
    }
}

📤 Output JSON:

{
  "car_id": 1,
  "brand": "BMW",
  "model": "M3 Competition",
  "year": 2024,
  "attributes": [
    {
      "attributeName": "color",
      "attributeValue": "Frozen Black"
    },
    {
      "attributeName": "engine",
      "attributeValue": "3.0L TwinPower Turbo"
    },
    {
      "attributeName": "transmission",
      "attributeValue": "8-Speed Automatic"
    },
    {
      "attributeName": "horsepower",
      "attributeValue": "503 HP"
    }
  ]
}

🔁 4. Deserialization (JSON → Object)

String jsonInput = """
    {
        "car_id": 2,
        "brand": "BMW",
        "model": "X5",
        "year": 2023,
        "attributes": [
            { "attributeName": "color",    "attributeValue": "Alpine White" },
            { "attributeName": "engine",   "attributeValue": "4.4L V8"      }
        ]
    }
    """;

ObjectMapper mapper = new ObjectMapper();
CarDTO car = mapper.readValue(jsonInput, CarDTO.class);

System.out.println("Brand : " + car.getBrand());
System.out.println("Model : " + car.getModel());
System.out.println("Attrs : " + car.getAttributes().size());

🎨 5. Custom Serializer

Sometimes you need full control over the JSON output. Use a custom serializer to reshape the attributes list into a flat key-value map:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;

public class CarDTOSerializer extends StdSerializer<CarDTO> {

    public CarDTOSerializer() {
        super(CarDTO.class);
    }

    @Override
    public void serialize(CarDTO car, 
                          JsonGenerator gen, 
                          SerializerProvider provider) throws IOException {

        gen.writeStartObject();

        gen.writeNumberField("car_id", car.getId());
        gen.writeStringField("brand",  car.getBrand());
        gen.writeStringField("model",  car.getModel());
        gen.writeNumberField("year",   car.getYear());

        // 🔑 Flatten attributes into a key-value object
        gen.writeObjectFieldStart("attributes");
        if (car.getAttributes() != null) {
            for (CarAttributeDTO attr : car.getAttributes()) {
                gen.writeStringField(
                    attr.getAttributeName(), 
                    attr.getAttributeValue()
                );
            }
        }
        gen.writeEndObject();

        gen.writeEndObject();
    }
}

Register the Custom Serializer:

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

SimpleModule module = new SimpleModule();
module.addSerializer(CarDTO.class, new CarDTOSerializer());
mapper.registerModule(module);

String json = mapper.writeValueAsString(car);
System.out.println(json);

📤 Output with Custom Serializer (flattened attributes):

{
  "car_id": 1,
  "brand": "BMW",
  "model": "M3 Competition",
  "year": 2024,
  "attributes": {
    "color": "Frozen Black",
    "engine": "3.0L TwinPower Turbo",
    "transmission": "8-Speed Automatic",
    "horsepower": "503 HP"
  }
}

🛡️ 6. Useful Jackson Annotations Summary

AnnotationPurpose
@JsonProperty("name")Rename a field in JSON
@JsonInclude(NON_NULL)Exclude null fields from output
@JsonIgnoreCompletely exclude a field from serialization
@JsonAliasAccept multiple names during deserialization
@JsonSerializeAttach a custom serializer to a field/class
@JsonDeserializeAttach a custom deserializer to a field/class
@JsonFormatFormat dates, numbers, etc.

✅ 7. Best Practices

🔹 Reuse ObjectMapper — it is thread-safe and expensive to create
🔹 Use @JsonInclude(NON_NULL) to keep JSON payloads clean
🔹 Prefer DTOs over Entities — never serialize JPA entities directly
🔹 Use custom serializers when you need full control over output format
🔹 Validate deserialized objects using Bean Validation (@Valid)


🎯 Conclusion

Jackson provides a rich, flexible API to handle JSON serialization in Java. By combining annotations, custom serializers, and the ObjectMapper, you can cleanly model complex relationships like Car → Attributes (one-to-many) and produce well-structured, efficient JSON payloads.


📚 Further Reading:

4/21/2026

Linux for DevOps (Beginners)

Linux for DevOps (Beginners)



1. Linux Fundamentals

1.1 What is Open Source?

Open-source software has source code freely available for anyone to view, modify, and distribute. Linux is built on open-source principles.

Key PointsDescription
Source codePublicly accessible
DevelopmentCommunity-driven
LicenseFree to use, modify, and redistribute
ExamplesLinux, Python, Firefox, Android

1.2 What is Linux?

Linux is a free, open-source operating system kernel created by Linus Torvalds in 1991. It powers many devices from smartphones to supercomputers.

AspectDetails
Kernel vs OSLinux is a kernel, not a full OS
Full OS ComponentsLinux Kernel + GNU tools + package manager + desktop environment
Popular Distributions (Distros)Ubuntu, Fedora, Debian, CentOS, Arch Linux
UsageServers, cloud, Android, IoT, supercomputers

1.3 Linux vs UNIX

SystemDescriptionNotes
LinuxFree, open-source kernel by Linus Torvalds (1991)Community-developed
UNIXProprietary OS from Bell Labs (1969)Not free
macOSUNIX-based (BSD), proprietary by AppleUNIX-based, proprietary
SimilaritiesBoth follow POSIX standardsLinux inspired by UNIX

1.4 Why Use Linux?

  • Free and open source — no licensing costs.
  • Highly secure — fewer viruses, strong permission model.
  • Stable and reliable — servers can run for years without reboot.
  • Lightweight — runs on old hardware.
  • Industry standard — most servers, cloud, and DevOps tools run on Linux.
  • Customizable — choose your own components and desktop environment.

1.5 Linux vs Windows

FeatureLinuxWindows
CostFreeRequires license
SecurityStrong permissions, fewer virusesMore vulnerable, requires antivirus
UsageDominates serversDominates desktops
CLI vs GUICLI-firstGUI-first
File Systemsext4, XFSNTFS, FAT32
Software InstallPackage managers (apt, yum)Installers (.exe)

1.6 What is a Kernel?

The kernel is the core of the operating system. It manages hardware resources and allows software to communicate with hardware.

FunctionsDescription
ManagesCPU, memory, I/O devices
ProvidesSystem calls for programs to request services
Acts asBridge between applications and hardware
Linux Kernel TypeMonolithic (all services run in kernel space)

2. Installing Ubuntu via WSL (Windows Subsystem for Linux)

WSL allows running a Linux terminal on Windows without a VM.

StepsCommands/Actions
Open PowerShell as AdministratorRun: wsl --install
Restart PCRestart your computer
Open UbuntuFrom Start Menu
Initial SetupSet username and password on first launch

Useful WSL Commands

CommandDescription
wsl --list --verboseList installed distros with details
wsl --set-default-version 2Set WSL version 2 as default
explorer.exe .Open Linux files in Windows Explorer

3. Basic Terminal Commands

3.1 Navigation

CommandDescription
pwdPrint working directory
lsList files and directories
ls -laList all files including hidden with details
cd <dir>Change directory
cd ..Go up one directory level
cd ~Go to home directory
cd /Go to root directory

3.2 File and Directory Operations

CommandDescription
mkdir <name>Create a new directory
mkdir -p a/b/cCreate nested directories
touch <file>Create empty file or update timestamp
rm <file>Remove a file
rm -r <dir>Remove directory and contents recursively
rm -zf <dir>Force remove without prompts (use carefully!)
cp <src> <dst>Copy a file
mv <src> <dst>Move or rename a file
cat <file>Display file contents
less <file>Scroll through file contents
nano <file>Open file in nano editor
vim <file>Open file in vim editor

3.3 File Permissions — chmod

SymbolValuePermission
r4Read
w2Write
x1Execute
CommandEffect
chmod 755 fileOwner: rwx, Group: r-x, Others: r-x
chmod 644 fileOwner: rw-, Group: r--, Others: r--
chmod +x fileAdd execute permission for all
chmod -w fileRemove write permission

3.4 Links

CommandDescription
ln <src> <link>Create hard link (same inode)
ln -s <src> <link>Create symbolic (soft) link
alias ll='ls -la'Create command alias (session only)

Note: Deleting original breaks soft link but not hard link.


4. File Handling & Text Processing

4.1 head & tail

CommandDescription
head <file>Show first 10 lines
head -n 20 <file>Show first 20 lines
tail <file>Show last 10 lines
tail -f <file>Follow file output live (logs)

4.2 wc — Word Count

CommandDescription
wc <file>Show lines, words, bytes
wc -l <file>Count lines only
wc -w <file>Count words only
wc -c <file>Count bytes/characters only

4.3 sort

CommandDescription
sort <file>Sort lines alphabetically
sort -r <file>Sort in reverse order
sort -n <file>Sort numerically
sort -u <file>Sort and remove duplicates
sort -k2 <file>Sort by 2nd column

4.4 grep — Search Text

CommandDescription
grep 'pattern' fileSearch for pattern in file
grep -i 'pattern' fileCase-insensitive search
grep -r 'pattern' dir/Recursive search in directory
grep -n 'pattern' fileShow line numbers with results
grep -v 'pattern' fileShow lines NOT matching pattern
grep -c 'pattern' fileCount matching lines
`grep -E 'p1p2' file`

4.5 find — File Search

CommandDescription
find . -name '*.txt'Find all .txt files in current directory
find / -name 'file.log'Find file across entire system
find . -type dFind only directories
find . -type fFind only regular files
find . -mtime -7Find files modified in last 7 days
find . -size +10MFind files larger than 10MB

4.6 awk — Text Processing

CommandDescription
awk '{print $1}' filePrint first column
awk '{print $1, $3}' filePrint columns 1 and 3
awk -F',' '{print $2}' fileUse comma as delimiter (CSV)
awk 'NR == 5' filePrint line number 5
awk '{sum+=$1} END {print sum}' fileSum all values in column 1

5. Disk Management & Archives

CommandDescription
df -hShow disk space usage (human-readable)
du -sh <dir>Show size of directory
du -h --max-depth=1Show sizes of subdirectories
lsblkList block devices (disks, partitions)

5.1 Zip / Unzip

CommandDescription
zip archive.zip file1 file2Create a zip archive
zip -r archive.zip dir/Zip an entire directory
unzip archive.zipExtract zip archive
unzip -l archive.zipList contents without extracting

5.2 tar — Tape Archive

CommandDescription
tar -cvf archive.tar dir/Create tar archive
tar -xvf archive.tarExtract tar archive
tar -czvf archive.tar.gz dir/Create compressed tar.gz archive
tar -xzvf archive.tar.gzExtract tar.gz archive
tar -tf archive.tarList contents of tar file

6. Process Management

6.1 View Processes

CommandDescription
psList processes for current user
ps auxList all processes with details
`ps auxgrep nginx`
topInteractive real-time viewer
htopImproved interactive process viewer
pgrep <name>Find process ID by name

6.2 Killing Processes

CommandDescription
kill <PID>Send SIGTERM (graceful stop)
kill -9 <PID>Send SIGKILL (force stop)
killall <name>Kill all processes by name
pkill <name>Kill process by pattern match

6.3 Background Jobs & nohup

CommandDescription
command &Run command in background
jobsList background jobs
fg %1Bring job 1 to foreground
bg %1Resume job 1 in background
Ctrl + ZSuspend current foreground job
nohup command &Run command immune to hangups (survives logout)
nohup command > out.log 2>&1 &Run nohup and save output to file
disown %1Remove job from shell job table

7. Remote Access

7.1 SSH — Secure Shell

CommandDescription
ssh user@hostConnect to remote server
ssh user@192.168.1.10Connect via IP address
ssh -p 2222 user@hostConnect on custom port
ssh-keygenGenerate SSH key pair
ssh-copy-id user@hostCopy public key to remote server
exitDisconnect SSH session

7.2 SCP — Secure Copy

CommandDescription
scp file.txt user@host:/path/Copy file TO remote server
scp user@host:/path/file.txt .Copy file FROM remote server
scp -r dir/ user@host:/path/Copy directory recursively
scp -P 2222 file user@host:/path/Use custom SSH port

7.3 GUI Tools

  • PuTTY — SSH/Telnet client for Windows
  • WinSCP — GUI file transfer for Windows (SFTP/SCP)
  • FileZilla — Cross-platform FTP/SFTP client

8. Package Management

8.1 apt-get (Debian/Ubuntu)

CommandDescription
sudo apt-get updateUpdate package list from repos
sudo apt-get upgradeUpgrade all installed packages
sudo apt-get install <pkg>Install a package
sudo apt-get remove <pkg>Remove a package
sudo apt-get autoremoveRemove unused dependencies
apt-cache search <keyword>Search for a package
dpkg -lList all installed packages

8.2 wget — Download Files

CommandDescription
wget <URL>Download file from URL
wget -O output.zip <URL>Download with custom filename
wget -c <URL>Resume interrupted download
wget -r <URL>Recursively download website

9. Scheduling & Automation

9.1 Cron Jobs

Cron is a time-based scheduler to run tasks automatically.

CommandDescription
crontab -eEdit cron jobs
crontab -lList current cron jobs
crontab -rRemove all cron jobs

Cron Syntax

* * * * * command
- - - - -
| | | | |
| | | | +---- Day of week (0-7, 0=Sun)
| | | +------ Month (1-12)
| | +-------- Day of month (1-31)
| +---------- Hour (0-23)
+------------ Minute (0-59)

Examples

ScheduleCommandDescription
0 2 * * * /backup.shRun backup daily at 2 AM
*/5 * * * * /check.shRun every 5 minutes
0 9 * * 1 /report.shRun every Monday at 9 AM
@reboot /startup.shRun at system startup

9.2 Apache Airflow (Overview)

  • Platform for authoring, scheduling, monitoring workflows.
  • Uses Python DAGs (Directed Acyclic Graphs).
  • Better suited than cron for complex, dependent tasks.
  • Provides web UI for monitoring.
  • Supports retries, alerts, and dependency management.

10. Shell Scripting

10.1 Getting Started

#!/bin/bash
echo 'Hello World'
chmod +x script.sh
./script.sh
  • #!/bin/bash — Shebang line specifying interpreter.
  • echo — Print to terminal.
  • chmod +x — Make script executable.
  • ./script.sh — Run script.

10.2 Variables

name='Alice'
echo $name
echo ${name}
read -p "Enter name: " name
  • Assign variable (no spaces around =).
  • Access variable with $.
  • Safer with ${}.
  • Read input from user.

10.3 Conditionals

if [ $age -gt 18 ]; then
  echo 'Adult'
elif [ $age -eq 18 ]; then
  echo 'Just 18'
else
  echo 'Minor'
fi
OperatorDescription
-eqEqual
-neNot equal
-gtGreater than
-ltLess than
-geGreater than or equal
-leLess than or equal
-zString is empty
-f fileFile exists and is regular
-d dirDirectory exists

10.4 Loops

for i in 1 2 3 4 5; do
  echo "Number $i"
done

10.5 Advanced Scripting Tips

  • Use set -e to exit on any error.
  • Use set -x for debug mode (prints commands).
  • Always quote variables "${var}" to handle spaces.
  • Use [[ ]] for advanced test features.
  • Trap signals for cleanup: trap 'cleanup' EXIT.

11. Quick Reference Cheat Sheet

Command GroupCommands / Description
Navigation Basicspwdlscd
File Operationsmkdirtouchrmcpmv
View File Contentscatlessheadtail
Search & Text Processinggrepfindawksortwc
Permissions Managementchmodchown
Links and Aliasesln -salias
Process Managementpstopkillnohup
Disk and Archivesdfdutarzip
Remote Accesssshscp
Package Managementapt-getwget
Scheduling Taskscrontab -e
Shell Scripting#!/bin/bashchmod +x


Efficient JSON serialization with Jackson and Java

  📌 Introduction JSON serialization is a fundamental part of modern Java applications — converting Java objects into JSON and back. Jackson...