Java JSON
最后修改于 2024 年 1 月 27 日
Java JSON 教程展示了如何在 Java 中使用 JSON-java 进行 JSON 序列化和反序列化。
JSON (JavaScript 对象表示法) 是一种轻量级的数据交换格式。 它易于人类阅读和编写,也易于机器解析和生成。 它比 XML 更简洁和更易读。 JSON 的官方互联网媒体类型是 application/json。 JSON 文件扩展名是 .json。 JSON 可以被 JavaScript 直接使用。
JSON-Java
JSON-Java 是一个 Java 序列化/反序列化库。 它将 JSON 文档解析为 Java 对象,并从 Java 类生成新的 JSON 文档。
JSON-Java 依赖
implementation 'org.json:json:20220924'
这是 JSON-Java 的 Gradle 依赖项。
JSON-Java 特性
这些是 JSON-Java 的特性
- 可靠且一致的结果。
- 无外部依赖。
- 符合 JSON 规范。
- 快速执行和低内存占用。
- 向后兼容。
Java JSONObject
JSONObject 是名称/值对的无序集合。 它的外部形式是一个字符串,用花括号括起来,名称和值之间用冒号分隔,值和名称之间用逗号分隔。
内部形式是一个对象,它具有用于按名称访问值的 get 和 opt 方法,以及用于按名称添加或替换值的 put 方法。
JSonObject 使用 toString 方法转换为 JSON 字符串。
package com.zetcode;
import org.json.JSONObject;
public class JSonObjectEx {
public static void main(String[] args) {
var user = new JSONObject();
user.put("name", "John Doe");
user.put("occupation", "gardener");
user.put("siblings", Integer.valueOf(2));
user.put("height", Double.valueOf(172.35));
user.put("married", Boolean.TRUE);
var userJson = user.toString();
System.out.println(userJson);
}
}
我们创建一个 JSONObject 并将其转换为 JSON 字符串。
{"siblings":2,"occupation":"gardener","name":"John Doe","married":true,"height":172.35}
这是最终的 JSON 字符串。
Java JSONObject 从 Map
在以下示例中,我们从 Map 创建一个 JSONObject。
package com.zetcode;
import org.json.JSONObject;
import java.util.HashMap;
public class JsonObjectFromMap {
public static void main(String[] args) {
var data = new HashMap<String, String>();
data.put("name", "John Doe");
data.put("occupation", "gardener");
data.put("siblings", "2");
data.put("height", "172.35");
data.put("married", "true");
var user = new JSONObject(data);
var userJson = user.toString();
System.out.println(userJson);
}
}
我们创建一个 HashMap。 该 map 被传递给 JSONObject 的构造函数。
Java 解析 JSON 字符串
在下一个示例中,我们解析一个 JSON 字符串。
package com.zetcode;
import org.json.JSONObject;
public class JsonParse {
public static void main(String[] args) {
String data = """
{"name": "John Doe",
"occupation": "gardener",
"siblings": "2",
"height": "172.35",
"married": "true"}""";
var user = new JSONObject(data);
System.out.println(user.get("name"));
System.out.println(user.get("occupation"));
System.out.println(user.get("siblings"));
}
}
只需将 JSON 字符串传递给 JSONObject 构造函数,即可将 JSON 字符串解析为 JSONObject。
John Doe gardener 2
我们从 JSONObject 中检索了三个值。
Java 类到 JSONObject
在以下示例中,我们将 Java 类转换为 JSONObject。
package com.zetcode;
import java.util.Objects;
public class User {
private String name;
private String occupation;
private int siblings;
private double height;
private boolean married;
public User(String name, String occupation, int siblings,
double height, boolean married) {
this.name = name;
this.occupation = occupation;
this.siblings = siblings;
this.height = height;
this.married = married;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public int getSiblings() {
return siblings;
}
public void setSiblings(int siblings) {
this.siblings = siblings;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public boolean isMarried() {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return siblings == user.siblings && Double.compare(user.height, height) == 0
&& married == user.married && Objects.equals(name, user.name)
&& Objects.equals(occupation, user.occupation);
}
@Override
public int hashCode() {
return Objects.hash(name, occupation, siblings, height, married);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("User{");
sb.append("name='").append(name).append('\'');
sb.append(", occupation='").append(occupation).append('\'');
sb.append(", siblings=").append(siblings);
sb.append(", height=").append(height);
sb.append(", married=").append(married);
sb.append('}');
return sb.toString();
}
}
我们有一个 User 类。
package com.zetcode;
import org.json.JSONObject;
public class Java2JsonObject {
public static void main(String[] args) {
var user = new User("John Doe", "gardener",
2, 172.35, true);
var userjo = new JSONObject(user);
System.out.println(userjo);
System.out.println(userjo.get("name"));
System.out.println(userjo.get("occupation"));
System.out.println(userjo.get("siblings"));
}
}
创建一个 User 对象。 该对象被传递给 JSONObject 的构造函数。 稍后,我们打印 JSONObject 的三个值。
Java JSONArray
JSONArray 是值的有序序列。 它的外部文本形式是一个字符串,用方括号括起来,值之间用逗号分隔。 构造函数可以将 JSON 文本转换为 Java 对象。 toString 方法转换为 JSON 文本。
package com.zetcode;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonArrayEx {
public static void main(String[] args) {
var user = new JSONObject();
user.put("name", "John Doe");
user.put("occupation", "gardener");
user.put("siblings", Integer.valueOf(2));
user.put("height", Double.valueOf(172.35));
user.put("married", Boolean.TRUE);
var cols = new JSONArray();
cols.put("red");
cols.put("blue");
cols.put("navy");
user.put("favCols", cols);
var userJson = user.toString();
System.out.println(userJson);
}
}
我们有一个表示用户的 JSONObject。 JSONArray 是用户最喜欢的颜色的列表。
{"siblings":2,"occupation":"gardener","name":"John Doe","married":true,
"favCols":["red","blue","navy"],"height":172.35}
在 JSON 中,数组表示为一对用逗号分隔值的方括号。
var userJson = new JSONObject(user);
var favCols = List.of("red", "blue", "navy");
userJson.put("favCols", favCols);
可以从 Java List 自动创建 JSONArray。
Java JSONWriter
JSONWriter 提供了一种快速便捷的方式来生成 JSON 文本。 这是一个低级流 API。
package com.zetcode;
import org.json.JSONWriter;
public class JsonWriterEx {
public static void main(String[] args) {
var user = new StringBuilder();
var writer = new JSONWriter(user);
writer.object();
writer.key("name").value("John Doe");
writer.key("occupation").value("gardener");
writer.key("siblings").value(2);
writer.key("married").value(true);
writer.key("favCols");
writer.array();
writer.value("red");
writer.value("blue");
writer.value("navy");
writer.endArray();
writer.endObject();
System.out.println(user);
}
}
该示例使用 JSONWriter 生成 JSON 字符串。
JSON-Java CDL
CDL 提供对 JSON 和逗号分隔列表之间进行转换的支持。
name, occupation, siblings, height, married John Doe, gardener, 2, 172.35, true Jane Doe, teacher, 1, 168.23, true Roger Roe, driver, 3, 178.59, false
这是 data.csv 文件。 它有三个用户并包含一个标题。
package com.zetcode;
import org.json.CDL;
import org.json.JSONArray;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class JsonParseCsv {
public static void main(String[] args) throws IOException {
var data = Files.readString(Paths.get("src/main/resources/data.csv"),
StandardCharsets.UTF_8);
JSONArray usersJson = CDL.toJSONArray(data);
usersJson.forEach(System.out::println);
}
}
该示例从 CSV 文件读取数据并将其转换为 JSON。
{"name":"John Doe","siblings":"2","occupation":"gardener","married":"true","height":"172.35"}
{"name":"Jane Doe","siblings":"1","occupation":"teacher","married":"true","height":"168.23"}
{"name":"Roger Roe","siblings":"3","occupation":"driver","married":"false","height":"178.59"}
Java JSON Web 应用程序
在以下示例中,我们从 Web 应用程序返回 JSON 数据。 我们使用 Undertow Web 服务器。
implementation 'org.json:json:20210307' implementation 'io.undertow:undertow-core:2.0.36.Final'
我们使用这两个依赖项。
package com.zetcode;
import java.util.Objects;
public class User {
private String name;
private String occupation;
private int siblings;
private double height;
private boolean married;
public User(String name, String occupation, int siblings,
double height, boolean married) {
this.name = name;
this.occupation = occupation;
this.siblings = siblings;
this.height = height;
this.married = married;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public int getSiblings() {
return siblings;
}
public void setSiblings(int siblings) {
this.siblings = siblings;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public boolean isMarried() {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return siblings == user.siblings && Double.compare(user.height, height) == 0
&& married == user.married && Objects.equals(name, user.name)
&& Objects.equals(occupation, user.occupation);
}
@Override
public int hashCode() {
return Objects.hash(name, occupation, siblings, height, married);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("User{");
sb.append("name='").append(name).append('\'');
sb.append(", occupation='").append(occupation).append('\'');
sb.append(", siblings=").append(siblings);
sb.append(", height=").append(height);
sb.append(", married=").append(married);
sb.append('}');
return sb.toString();
}
}
我们有一个 User 类。
package com.zetcode;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import org.json.JSONArray;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class UsersHandler implements HttpHandler {
List<User> users = List.of(new User("John Doe", "gardener", 2, 172.35, true),
new User("Jane Doe", "teacher", 1, 168.23, true),
new User("Roger Roe", "driver", 3, 178.59, false));
@Override
public void handleRequest(HttpServerExchange exchange) {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
JSONArray usersJson = new JSONArray(users);
exchange.getResponseSender().send(usersJson.toString(), StandardCharsets.UTF_8);
}
}
在 handleRequest 方法中,我们将响应的内容类型设置为 application/json 并在 send 方法中发送 JSON 字符串。 JSON 字符串是用户数组。
package com.zetcode;
import io.undertow.Undertow;
import static io.undertow.Handlers.path;
public class JsonWebApp {
public static void main(String[] args) {
Undertow server = Undertow.builder()
.addHttpListener(8080, "0.0.0.0")
.setHandler(path().addPrefixPath("/users", new UsersHandler()))
.build();
server.start();
}
}
在 JsonWebApp 中,我们设置 Web 应用程序。 UsersHandler 映射到 /users 端点。
$ curl localhost:8080/users
[{"siblings":2,"occupation":"gardener","name":"John Doe","married":true,"height":172.35},
{"siblings":1,"occupation":"teacher","name":"Jane Doe","married":true,"height":168.23},
{"siblings":3,"occupation":"driver","name":"Roger Roe","married":false,"height":178.59}]
我们启动应用程序并使用 curl 生成请求。
来源
在本文中,我们展示了如何使用 JSON-java 库在 Java 中使用 JSON。
作者
列出所有Java教程。