在 Java 中处理 JSON 数据时,获取 key(键)的值取决于你使用的 JSON 库,以下是几种常见 JSON 库(如 org.json、Gson、Jackson、Fastjson)的示例代码,展示如何获取 key 的值。
使用 org.json 库
org.json 是一个轻量级 JSON 库,适合简单场景。
示例 JSON 数据:
{
"name": "Alice",
"age": 25,
"isStudent": true,
"address": {
"city": "New York",
"zip": "10001"
}
}
代码示例:
import org.json.JSONObject;
public class OrgJsonExample {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"Alice\",\"age\":25,\"isStudent\":true,\"address\":{\"city\":\"New York\",\"zip\":\"10001\"}}";
JSONObject jsonObject = new JSONObject(jsonStr);
// 获取简单 key 的值
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean isStudent = jsonObject.getBoolean("isStudent");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Is Student: " + isStudent);
// 获取嵌套 JSON 对象
JSONObject address = jsonObject.getJSONObject("address");
String city = address.getString("city");
String zip = address.getString("zip");
System.out.println("City: " + city);
System.out.println("Zip: " + zip);
// 检查 key 是否存在
if (jsonObject.has("name")) {
System.out.println("Key 'name' exists!");
}
}
}
常用方法:
getString(key):获取字符串值。getInt(key):获取整数值。getBoolean(key):获取布尔值。getJSONObject(key):获取嵌套的 JSON 对象。has(key):检查 key 是否存在。
使用 Gson 库(Google Gson)
Gson 是 Google 提供的 JSON 库,适合将 JSON 映射到 Java 对象。
定义 Java 类:
public class Person {
private String name;
private int age;
private boolean isStudent;
private Address address;
// Getters and Setters
public static class Address {
private String city;
private String zip;
// Getters and Setters
}
}
代码示例:
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"Alice\",\"age\":25,\"isStudent\":true,\"address\":{\"city\":\"New York\",\"zip\":\"10001\"}}";
Gson gson = new Gson();
// 解析 JSON 到 Java 对象
Person person = gson.fromJson(jsonStr, Person.class);
// 获取 key 的值
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("Is Student: " + person.isStudent());
System.out.println("City: " + person.getAddress().getCity());
System.out.println("Zip: " + person.getAddress().getZip());
}
}
特点:
- 需要定义 Java 类来映射 JSON 结构。
- 适合复杂 JSON 数据的解析。
使用 Jackson 库(高性能 JSON 库)
Jackson 是 Java 生态中最流行的 JSON 库之一。
定义 Java 类(同 Gson):
public class Person {
private String name;
private int age;
private boolean isStudent;
private Address address;
// Getters and Setters
public static class Address {
private String city;
private String zip;
// Getters and Setters
}
}
代码示例:
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonExample {
public static void main(String[] args) throws Exception {
String jsonStr = "{\"name\":\"Alice\",\"age\":25,\"isStudent\":true,\"address\":{\"city\":\"New York\",\"zip\":\"10001\"}}";
ObjectMapper objectMapper = new ObjectMapper();
// 解析 JSON 到 Java 对象
Person person = objectMapper.readValue(jsonStr, Person.class);
// 获取 key 的值
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("Is Student: " + person.isStudent());
System.out.println("City: " + person.getAddress().getCity());
System.out.println("Zip: " + person.getAddress().getZip());
}
}
特点:
- 性能高,功能强大。
- 支持 JSON 流式解析(
JsonParser)和树模型(JsonNode)。
使用 Fastjson(阿里巴巴 JSON 库)
Fastjson 是阿里巴巴的高性能 JSON 库。
代码示例:
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
public class FastjsonExample {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"Alice\",\"age\":25,\"isStudent\":true,\"address\":{\"city\":\"New York\",\"zip\":\"10001\"}}";
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
// 获取简单 key 的值
String name = jsonObject.getString("name");
int age = jsonObject.getIntValue("age");
boolean isStudent = jsonObject.getBooleanValue("isStudent");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Is Student: " + isStudent);
// 获取嵌套 JSON 对象
JSONObject address = jsonObject.getJSONObject("address");
String city = address.getString("city");
String zip = address.getString("zip");
System.out.println("City: " + city);
System.out.println("Zip: " + zip);
// 使用 JSONPath 获取值(更灵活)
String cityViaPath = (String) JSONPath.eval(jsonObject, "$.address.city");
System.out.println("City (via JSONPath): " + cityViaPath);
}
}
特点:
- 支持 JSONPath 查询(类似 XPath)。
- 性能极高,但安全性问题需注意(如
autoType开启可能导致漏洞)。
获取所有 Key(遍历 JSON)
如果需要获取 JSON 的所有 key,可以使用以下方法:
org.json 示例:
JSONObject jsonObject = new JSONObject(jsonStr);
for (String key : jsonObject.keySet()) {
System.out.println("Key: " + key + ", Value: " + jsonObject.get(key));
}
Jackson 示例(使用 JsonNode):
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonStr);
Iterator<String> fieldNames = rootNode.fieldNames();
while (fieldNames.hasNext()) {
String key = fieldNames.next();
System.out.println("Key: " + key + ", Value: " + rootNode.get(key));
}
| 库 | 适用场景 | 获取 key 的方式 |
|---|---|---|
org.json |
简单 JSON 解析 | jsonObject.getString("key") |
Gson |
复杂 JSON → Java 对象映射 | gson.fromJson(json, Person.class) |
Jackson |
高性能、流式解析 | objectMapper.readValue(json, Person.class) |
Fastjson |
高性能、支持 JSONPath | jsonObject.getString("key") 或 JSONPath.eval() |
选择合适的库取决于你的需求:
- 简单场景 →
org.json - 复杂对象映射 →
Gson或Jackson - 高性能需求 →
Fastjson或Jackson
