Module jakarta.json.bind
JsonbBuilder is the starting point to
create a Jsonb instance, which is then used
to serialise and deserialise Java objects.
JSON property names
Names from fields and record components
The examples below demonstrate how JSON-B maps a string, a boolean, a number, an array, a nested object, and an enum:
public class Planet {
public String name;
public boolean isHabitable;
public long mass;
public List<String> moons;
public Star star;
}
public record Star(String name, StarType type) {}
public enum StarType { MAIN_SEQUENCE, GIANT, DWARF }
Conversion of a Java object to JSON and then back to a Java object:
Jsonb jsonb = JsonbBuilder.create();
Planet mars = new Planet();
mars.name = "Mars";
mars.isHabitable = false;
mars.mass = 641693L;
mars.moons = List.of("Phobos", "Deimos");
mars.star = new Star("Sol", StarType.MAIN_SEQUENCE);
String json = jsonb.toJson(mars);
// Generated JSON:
// {
// "name": "Mars",
// "isHabitable": false,
// "mass": 641693,
// "moons": ["Phobos", "Deimos"],
// "star": {
// "name": "Sol",
// "type": "MAIN_SEQUENCE"
// }
// }
Planet planet = jsonb.fromJson(json, Planet.class);
// Close if no longer needed; a Jsonb instance should be reused throughout the application.
jsonb.close();
Names from accessor methods
A JSON property name can be derived from the name of an accessor method with
public visibility. In the following class the period field
is package-private, so it does not determine the name of a JSON property.
The field is exposed through accessor methods named getOrbitalPeriod
and setOrbitalPeriod, so the JSON property name is
"orbitalPeriod":
public class Comet {
String name;
int period;
public String getName() { return name; }
public int getOrbitalPeriod() { return period; }
public void setName(String value) { name = value; }
public void setOrbitalPeriod(int value) { period = value; }
}
String json = """
{
"name": "Halley",
"orbitalPeriod": 75
}
""";
Comet comet = jsonb.fromJson(json, Comet.class);
String name = comet.getName(); // "Halley"
int period = comet.getOrbitalPeriod(); // 75
For advanced configuration (custom serializers, date formats, property
naming strategies, etc.) see JsonbConfig.
- See Also:
-
Packages
ExportsPackageDescriptionProvides the JSON Binding API, which enables binding Java objects to and from JSON documents.Defines adapter related classes.Defines annotations for customizing the mapping between Java program elements and JSON documents.Defines strategies and policies for customizing the mapping between Java program elements and JSON documents.Defines serializer depending classes.Service Provider Interface (SPI) to plug in implementations of JSON Binding APIJsonbBuilderobjects.