杰瑞科技汇

JSON的null值在Java中如何处理?

Of course! This is a fundamental concept in working with JSON in Java. Let's break down how null is handled in JSON and how it maps to Java.

The JSON null Value

In JSON, null is a literal that represents the absence of a value. It's distinct from an empty string (), zero (0), or an empty array/object ([], ). It simply means "no value here".

Example JSON:

{
  "userId": 123,
  "username": "john_doe",
  "email": null,
  "lastLogin": null,
  "isActive": true,
  "permissions": []
}

In this example, email and lastLogin are explicitly set to null, indicating that the user has not provided an email or has never logged in.


The Java null Reference

In Java, null is a special literal that represents a reference to nothing. It means that a variable of an object type does not point to any object in memory.

String email = null;
Date lastLogin = null;

The Mapping: JSON null ↔ Java null

This is the most straightforward mapping. A JSON null value is directly and universally represented by a Java null reference.

JSON Value Java Equivalent Description
null null The absence of a value.

This mapping is consistent across all major JSON libraries in Java (Jackson, Gson, org.json).


How JSON Libraries Handle null in Java

When you parse JSON into Java objects (deserialization) or serialize Java objects into JSON, the libraries handle this mapping automatically.

A. Parsing JSON (Deserialization)

Let's use the Jackson library, which is the most common one in the Java ecosystem (used by Spring Boot, etc.).

JSON Input:

{
  "name": "Alice",
  "city": null
}

Java POJO (Plain Old Java Object):

public class User {
    private String name;
    private String city;
    // Getters and Setters are required by Jackson
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getCity() { return city; }
    public void setCity(String city) { this.city = city; }
    @Override
    public String toString() {
        return "User{name='" + name + "', city='" + city + "'}";
    }
}

Code to Parse JSON:

import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonParser {
    public static void main(String[] args) throws Exception {
        String json = "{\"name\":\"Alice\",\"city\":null}";
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(json, User.class);
        System.out.println(user);
    }
}

Result:

User{name='Alice', city='null'}

Notice that user.getCity() returns null. The JSON library correctly mapped the JSON null to the Java null reference.

B. Generating JSON (Serialization)

Now, let's do the reverse. Start with a Java object that has a null field and serialize it to JSON.

Java Object:

User user = new User();
user.setName("Bob");
user.setCity(null); // Explicitly setting city to null

Code to Generate JSON:

import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonGenerator {
    public static void main(String[] args) throws Exception {
        User user = new User();
        user.setName("Bob");
        user.setCity(null);
        ObjectMapper mapper = new ObjectMapper();
        // To make the output pretty, you can use:
        // mapper.enable(SerializationFeature.INDENT_OUTPUT);
        String json = mapper.writeValueAsString(user);
        System.out.println(json);
    }
}

Result:

{"name":"Bob","city":null}

The Jackson library correctly serialized the Java null reference to the JSON null value.


Common Scenarios & Best Practices

Handling null Fields in Serialization (Omitting null fields)

Sometimes, you don't want to include fields with null values in your final JSON output. Most libraries provide configuration for this.

With Jackson: You can use the @JsonInclude annotation on the POJO class or field.

import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL) // Exclude all null fields
public class User {
    private String name;
    private String city; // This field will be omitted from the JSON if null
    // ... getters and setters
}

Serialization Code:

User user = new User();
user.setName("Charlie");
user.setCity(null);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
System.out.println(json);

Output:

{"name":"Charlie"}

The city field is gone because its value was null.

Handling null in Collections

What if a collection itself is null?

JSON:

{
  "username": "diana",
  "roles": null
}

Java:

public class User {
    private String username;
    private List<String> roles; // roles can be null
    // ... getters and setters
}

This maps perfectly. user.getRoles() will return null.

If you want to ensure a collection is never null (e.g., to always have an empty list), you can initialize it in the constructor.

public class User {
    private List<String> roles = new ArrayList<>(); // Never null!
    // ... constructor and other fields
}

In this case, if the JSON has "roles": null, Jackson will typically throw an exception unless configured otherwise, because it's trying to put a null value into a non-nullable collection field. You can use @JsonSetter(nulls = Nulls.SKIP) to tell Jackson to ignore null values for that field.

Summary

Concept JSON Java How it's Handled
Literal Value null null Direct 1-to-1 mapping. A JSON null becomes a Java null reference, and vice-versa.
Serialization {"field": null} object.setField(null) The library serializes the Java null reference to the JSON null value.
Deserialization {"field": null} String field = object.getField(); // returns null The library deserializes the JSON null value into a Java null reference.
Exclusion (Field is omitted) @JsonInclude(Include.NON_NULL) The library can be configured to skip fields with null values during serialization.
分享:
扫描分享到社交APP
上一篇
下一篇