Converting Java Objects to JSON Strings with Gson: Formatting and Field Extraction

JSON Format

JSON (JavaScript Object Notation) is a lightweight data interchange format that follows these structural rules:

Data consists of key-value pairs where keys must be strings, and values can be one of several data types:

  • Numbers (integers or floating-point values)
  • Strings (enclosed in double quotes)
  • Booleans (true or false)
  • null
  • Objects (nested JSON objects wrapped in curly braces {})
  • Arrays (ordered collections wrapped in square brackets [])
  • Multiple key-value pairs are separated by commas

The entire structure is wrapped in curly braces {}.

Example 1: Simple JSON Object

{
  "name": "John Doe",
  "age": 30,
  "isEmployed": true,
  "city": "New York"
}

This JSON object contains four key-value pairs where "name" maps to a string, "age" maps to a number, "isEmployed" maps to a boolean, and "city" maps to another string.

Example 2: Nested JSON Objects

{
  "person": {
    "name": "Jane Smith",
    "contact": {
      "phone": "+1-555-1234",
      "email": "jane.smith@example.com"
    }
  },
  "company": {
    "name": "Acme Inc.",
    "address": {
      "street": "1 Main St",
      "city": "San Francisco",
      "country": "USA"
    }
  }
}

This example demonstrates nesting where the outer object contains "person" and "company" keys, each mapping to nested JSON objects with their own porperties.

Example 3: JSON Arrays

{
  "employees": [
    {
      "firstName": "Bill",
      "lastName": "Gates"
    },
    {
      "firstName": "George",
      "lastName": "Bush"
    },
    {
      "firstName": "Thomas",
      "lastName": "Carter"
    }
  ]
}

The "employees" key maps to an array containing three objects, each representing an employee's first and last name.

Example 4: Objects and Arrays Combined

{
  "menu": {
    "id": "file",
    "value": "File",
    "popup": {
      "menuitem": [
        {"value": "New", "onclick": "CreateNewDoc()"},
        {"value": "Open", "onclick": "OpenDoc()"},
        {"value": "Close", "onclick": "CloseDoc()"}
      ]
    }
  }
}

This structure shows a nested object containing an array of menu items, each with its own properties.

Converting Java Objects to JSON with Gson

Add the following dependency to your project:

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

Supported Data Types

The Gson library's toJson() method supports the following Java types:

1. Primitive Types and Wrappers:

  • boolean / Boolean
  • byte / Byte
  • short / Short
  • int / Integer
  • long / Long
  • float / Float
  • double / Double
  • char / Character
  • String

2. Arrays:

  • Primitive arrays (int[], String[])
  • Object arrays (MyClass[])

3. Collections:

  • List implementations (ArrayList)
  • Set implementations (HashSet)
  • Map<K, V> (HashMap<String, MyClass>). Keys must be serializable, typically String or numeric types.

4. Custom Classes:

  • POJOs with fields and getter/setter methods. Gson converts properties to JSON key-value pairs.
  • Properties can be primitives, arrays, collections, or other custom classes.
  • Annotations like @Expose and @SerializedName control serialization behavior and field names.
  • Enums: Constants are serialized as strings using the constant name or @SerializedName value.

5. Special Types:

  • Date objects: Converted to milliseconds since Unix epoch by default. Configure custom date formats via GsonBuilder.
  • null values: Serialized as JSON null.

Basic Serialization

System.out.println(new Gson().toJson(response));

Breaking down this single line:

  1. new Gson() instantiates the Gson class, Google's library for JSON processing
  2. .toJson(response) serializes the response object into a JSON-formatted string, recursively handling nested objects and arrays
  3. System.out.println() outputs the resulting JSON string to the console

Complete Example

public class Student {
    private int age = 0;
    private String name = "";
    private int classGrade = 0;

    public Student(int age, String name, int classGrade) {
        this.age = age;
        this.name = name;
        this.classGrade = classGrade;
    }
}
import com.google.gson.Gson;

public class Main {
    public static void main(String[] args) {
        Student student = new Student(18, "wang", 100);
        System.out.println(new Gson().toJson(student));
    }
}

Output:

{"age":18,"name":"wang","classGrade":100}

The student object converts to JSON, but the output appears as a single line without formatting.

Pretty Printing JSON Output

GsonBuilder's setPrettyPrinting() method adds indentation and line breaks:

System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(student));

Step-by-step explanation:

  • new GsonBuilder() creates a builder for configuring Gson instances with custom serialization options
  • .setPrettyPrinting() enables formatted output with proper indentation and newlines
  • .create() generates the configured Gson instance
  • .toJson(student) serializes the object to formatted JSON
  • System.out.println() displays the result

Pretty-printed output:

{
  "age": 18,
  "name": "wang",
  "classGrade": 100
}

Extracting Specific Fields from JSON

Process involves three steps: parse the JSON string, retreive the field, and convert the JsonElement to the desired type.

Step 1: Parse JSON String to JsonObject

String jsonString = new GsonBuilder().setPrettyPrinting().create().toJson(student);
JsonObject jsonObject = new Gson().fromJson(jsonString, JsonObject.class);

Step 2: Retrieve Specific Field

JsonElement ageElement = jsonObject.get("age");

Stepp 3: Convert JsonElement to Target Type

if (ageElement != null && !ageElement.isJsonNull()) {
    if (ageElement.isJsonPrimitive() && ageElement.getAsJsonPrimitive().isNumber()) {
        int ageValue = ageElement.getAsInt();
        System.out.println("Age: " + ageValue);
    }
}

Type-specific extraction methods:

Numeric values:

if (fieldValue.isJsonPrimitive() && fieldValue.getAsJsonPrimitive().isNumber()) {
    int intValue = fieldValue.getAsInt();
    long longValue = fieldValue.getAsLong();
    double doubleValue = fieldValue.getAsDouble();
}

Boolean values:

if (fieldValue.isJsonPrimitive() && fieldValue.getAsJsonPrimitive().isBoolean()) {
    boolean boolValue = fieldValue.getAsBoolean();
}

Nested JSON objects:

if (fieldValue.isJsonObject()) {
    JsonObject nestedObject = fieldValue.getAsJsonObject();
}

JSON arrays:

if (fieldValue.isJsonArray()) {
    JsonArray arrayValue = fieldValue.getAsJsonArray();
}

Handling null values:

if (fieldValue == null || fieldValue.isJsonNull()) {
    // Handle missing or null fields
}

Complete field extraction example:

public static String extractField(JsonObject jsonObject, String fieldName) {
    JsonElement value = jsonObject.get(fieldName);
    
    if (value == null || value.isJsonNull()) {
        return null;
    }
    
    if (value.isJsonPrimitive()) {
        JsonPrimitive primitive = value.getAsJsonPrimitive();
        if (primitive.isString()) {
            return primitive.getAsString();
        } else if (primitive.isNumber()) {
            return String.valueOf(primitive.getAsInt());
        } else if (primitive.isBoolean()) {
            return String.valueOf(primitive.getAsBoolean());
        }
    } else if (value.isJsonObject()) {
        return value.getAsJsonObject().toString();
    } else if (value.isJsonArray()) {
        return value.getAsJsonArray().toString();
    }
    
    return null;
}

Tags: java JSON gson serialization JSON Parsing

Posted on Sun, 14 Jun 2026 18:03:09 +0000 by furious5