{
"name": "Falco",
"age": 3,
"bitable": false
}
public static void main(String[] args) {
// Create Json and serialize
JsonObject json = Json.createObjectBuilder()
.add("name", "Falco")
.add("age", BigDecimal.valueOf(3))
.add("biteable", Boolean.FALSE).build();
String result = json.toString();
System.out.println(result);
}
public static void main(String[] args) {
// Parse back
final String result = "{\"name\":\"Falco\",\"age\":3,\"bitable\":false}";
final JsonParser parser = Json.createParser(new StringReader(result));
String key = null;
String value = null;
while (parser.hasNext()) {
final Event event = parser.next();
switch (event) {
case KEY_NAME:
key = parser.getString();
System.out.println(key);
break;
case VALUE_STRING:
value = parser.getString();
System.out.println(value);
break;
}
}
parser.close();
}
官方示例
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(someObject);
// Create custom configuration
JsonbConfig config = new JsonbConfig()
.withNullValues(true)
.withFormating(true);
// Create Jsonb with custom configuration
Jsonb jsonb = JsonbBuilder.create(config);
// Use it!
String result = jsonb.toJson(someObject);
<!-- https://mvnrepository.com/artifact/jakarta.json.bind/jakarta.json.bind-api -->
<dependency>
<groupId>jakarta.json.bind</groupId>
<artifactId>jakarta.json.bind-api</artifactId>
<version>1.0.1</version>
</dependency>
public class User {
public long id;
public String name;
public int age;
}
Jsonb jsonb = JsonbBuilder.create();
User bob = new User();
bob.id = 1234;
bob.name = "Bob";
bob.age = 42;
String bobJson = jsonb.toJson(bob);
System.out.println(bobJson); // {"id":1234,"name":"Bob","age":42}
Jsonb jsonb = JsonbBuilder.create();
String aliceJson = "{\"id\":5678,\"name\":\"Alice\",\"age\":42}";
User alice = jsonb.fromJson(aliceJson, User.class);
实际开发中应该结合JSON-P和JSON-B一起使用。