目录
[一、 FastJSON](#一、 FastJSON)
[1)解析 JSON 字符串为 Java 对象](#1)解析 JSON 字符串为 Java 对象)
[2)处理嵌套的 JSON 结构(创建java对象)](#2)处理嵌套的 JSON 结构(创建java对象))
[3)处理嵌套的 JSON 结构(直接从 JSON 对象中获取值)](#3)处理嵌套的 JSON 结构(直接从 JSON 对象中获取值))
[4)处理嵌套的 JSON 结构(使用路径表达式)](#4)处理嵌套的 JSON 结构(使用路径表达式))
[2)直接从 JSON 对象中获取值](#2)直接从 JSON 对象中获取值)
[1)解析为 Java 对象](#1)解析为 Java 对象)
[2)直接从 JSON 对象中获取值](#2)直接从 JSON 对象中获取值)
[2)使用递归遍历 JSON 对象](#2)使用递归遍历 JSON 对象)
一、 FastJSON
1)解析 JSON 字符串为 Java 对象
存在一个json字符串:{"name":"John","age":30,"isStudent":false}
//定义一个 Java 类来对应这个 JSON 结构
class Person {
private String name;
private int age;
private boolean isStudent;
// 生成相应的 getter 和 setter 方法
}
直接从 JSON 对象中获取值
import com.alibaba.fastjson.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"John\",\"age\":30,\"isStudent\":false}";
JSONObject jsonObject = JSON.parseObject(jsonStr);
String name = jsonObject.getString("name");
int age = jsonObject.getInteger("age");
boolean isStudent = jsonObject.getBooleanValue("isStudent");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Is Student: " + isStudent);
}
}
2)处理嵌套的 JSON 结构(创建java对象)
已知存在一个josn:{"person":{"name":"John","age":30},"address":{"city":"New York","country":"USA"}}
//定义对应的 Java 类
class Person {
private String name;
private int age;
// getter 和 setter 方法
}
class Address {
private String city;
private String country;
// getter 和 setter 方法
}
class RootObject {
private Person person;
private Address address;
// getter 和 setter 方法
}
解析:
import com.alibaba.fastjson.JSON;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"person\":{\"name\":\"John\",\"age\":30},\"address\":{\"city\":\"New York\",\"country\":\"USA\"}}";
RootObject rootObject = JSON.parseObject(jsonStr, RootObject.class);
Person person = rootObject.getPerson();
Address address = rootObject.getAddress();
String name = person.getName();
int age = person.getAge();
String city = address.getCity();
String country = address.getCountry();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
System.out.println("Country: " + country);
}
}
3)处理嵌套的 JSON 结构(直接从 JSON 对象中获取值)
存在json串:
{"user":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}
import com.alibaba.fastjson.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"user\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
JSONObject jsonObject = JSON.parseObject(jsonStr);
JSONObject userObject = jsonObject.getJSONObject("user");
String userName = userObject.getString("name");
int userAge = userObject.getInteger("age");
JSONObject addressObject = userObject.getJSONObject("address");
String city = addressObject.getString("city");
String country = addressObject.getString("country");
JSONArray ordersArray = jsonObject.getJSONArray("orders");
for (int i = 0; i < ordersArray.size(); i++) {
JSONObject orderObject = ordersArray.getJSONObject(i);
int orderId = orderObject.getInteger("id");
String product = orderObject.getString("product");
System.out.println("Order ID: " + orderId + ", Product: " + product);
}
System.out.println("User Name: " + userName);
System.out.println("User Age: " + userAge);
System.out.println("City: " + city);
System.out.println("Country: " + country);
}
}
4)处理嵌套的 JSON 结构(使用路径表达式)
存在json串:
{"user":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}
import com.alibaba.fastjson.JSONPath;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"user\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
String userName = (String) JSONPath.read(jsonStr, "$.user.name");
int userAge = (int) JSONPath.read(jsonStr, "$.user.age");
String city = (String) JSONPath.read(jsonStr, "$.user.address.city");
String country = (String) JSONPath.read(jsonStr, "$.user.address.country");
Object[] orders = JSONPath.read(jsonStr, "$.orders");
for (Object order : orders) {
int orderId = (int) JSONPath.read(order, "$.id");
String product = (String) JSONPath.read(order, "$.product");
System.out.println("Order ID: " + orderId + ", Product: " + product);
}
System.out.println("User Name: " + userName);
System.out.println("User Age: " + userAge);
System.out.println("City: " + city);
System.out.println("Country: " + country);
}
}
二、Jackson
1)创建java对象
已知存在json串:
{"person":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}
class Address {
private String city;
private String country;
// Getters and setters
}
class Order {
private int id;
private String product;
// Getters and setters
}
class Person {
private String name;
private int age;
private Address address;
// Getters and setters
}
class RootObject {
private Person person;
private Order[] orders;
// Getters and setters
}
使用 Jackson 进行解析到对象中
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) throws Exception {
String jsonStr = "{\"person\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
ObjectMapper objectMapper = new ObjectMapper();
RootObject rootObject = objectMapper.readValue(jsonStr, RootObject.class);
String name = rootObject.getPerson().getName();
int age = rootObject.getPerson().getAge();
String city = rootObject.getPerson().getAddress().getCity();
String country = rootObject.getPerson().getAddress().getCountry();
Order[] orders = rootObject.getOrders();
for (Order order : orders) {
int orderId = order.getId();
String product = order.getProduct();
System.out.println("Order ID: " + orderId + ", Product: " + product);
}
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
System.out.println("Country: " + country);
}
}
2)直接从 JSON 对象中获取值
已知存在json串:
{"person":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) throws Exception {
String jsonStr = "{\"person\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonStr);
JsonNode personNode = rootNode.get("person");
String name = personNode.get("name").asText();
int age = personNode.get("age").asInt();
JsonNode addressNode = personNode.get("address");
String city = addressNode.get("city").asText();
String country = addressNode.get("country").asText();
JsonNode ordersNode = rootNode.get("orders");
for (JsonNode orderNode : ordersNode) {
int orderId = orderNode.get("id").asInt();
String product = orderNode.get("product").asText();
System.out.println("Order ID: " + orderId + ", Product: " + product);
}
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
System.out.println("Country: " + country);
}
}
三、Gson
1)解析为 Java 对象
已知存在json串:{"person":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}
定义对应的 Java 类:
class Address {
private String city;
private String country;
// Getters and setters
}
class Order {
private int id;
private String product;
// Getters and setters
}
class Person {
private String name;
private int age;
private Address address;
// Getters and setters
}
class RootObject {
private Person person;
private Order[] orders;
// Getters and setters
}
使用 Gson 进行解析:
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"person\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
Gson gson = new Gson();
RootObject rootObject = gson.fromJson(jsonStr, RootObject.class);
String name = rootObject.getPerson().getName();
int age = rootObject.getPerson().getAge();
String city = rootObject.getPerson().getAddress().getCity();
String country = rootObject.getPerson().getAddress().getCountry();
Order[] orders = rootObject.getOrders();
for (Order order : orders) {
int orderId = order.getId();
String product = order.getProduct();
System.out.println("Order ID: " + orderId + ", Product: " + product);
}
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
System.out.println("Country: " + country);
}
}
2)直接从 JSON 对象中获取值
已知存在json串:{"person":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}
不创建 Java 对象,直接从 JSON 对象获取值:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"person\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
JsonObject jsonObject = JsonParser.parseString(jsonStr).getAsJsonObject();
JsonObject personObject = jsonObject.getAsJsonObject("person");
String name = personObject.get("name").getAsString();
int age = personObject.get("age").getAsInt();
JsonObject addressObject = personObject.getAsJsonObject("address");
String city = addressObject.get("city").getAsString();
String country = addressObject.get("country").getAsString();
JsonArray ordersArray = jsonObject.getAsJsonArray("orders");
for (JsonElement orderElement : ordersArray) {
JsonObject orderObject = orderElement.getAsJsonObject();
int orderId = orderObject.get("id").getAsInt();
String product = orderObject.get("product").getAsString();
System.out.println("Order ID: " + orderId + ", Product: " + product);
}
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
System.out.println("Country: " + country);
}
}
四、org.json
1)解析为 JSONObject****对象
已知存在json串:{"person":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}
使用org.json
解析:
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonStr = "{\"person\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
JSONObject jsonObject = new JSONObject(jsonStr);
// 获取 person 对象
JSONObject personObject = jsonObject.getJSONObject("person");
String name = personObject.getString("name");
int age = personObject.getInt("age");
// 获取 address 对象
JSONObject addressObject = personObject.getJSONObject("address");
String city = addressObject.getString("city");
String country = addressObject.getString("country");
// 获取 orders 数组
JSONArray ordersArray = jsonObject.getJSONArray("orders");
for (int i = 0; i < ordersArray.length(); i++) {
JSONObject orderObject = ordersArray.getJSONObject(i);
int orderId = orderObject.getInt("id");
String product = orderObject.getString("product");
System.out.println("Order ID: " + orderId + ", Product: " + product);
}
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
System.out.println("Country: " + country);
}
}
2)使用递归遍历 JSON 对象
已知存在json串:已知存在json串:{"person":{"name":"Alice","age":25,"address":{"city":"New York","country":"USA"}},"orders":[{"id":1,"product":"Book"},{"id":2,"product":"Pen"}]}
如果 JSON 结构更加复杂,可以使用递归的方式遍历获取值。
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void traverseJSON(JSONObject jsonObject) {
for (String key : JSONObject.getNames(jsonObject)) {
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
traverseJSON((JSONObject) value);
} else if (value instanceof JSONArray) {
JSONArray array = (JSONArray) value;
for (int i = 0; i < array.length(); i++) {
Object item = array.get(i);
if (item instanceof JSONObject) {
traverseJSON((JSONObject) item);
} else {
// 处理基本类型的值
System.out.println(key + ": " + item);
}
}
} else {
// 处理基本类型的值
System.out.println(key + ": " + value);
}
}
}
public static void main(String[] args) {
String jsonStr = "{\"person\":{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}},\"orders\":[{\"id\":1,\"product\":\"Book\"},{\"id\":2,\"product\":\"Pen\"}]}";
JSONObject jsonObject = new JSONObject(jsonStr);
traverseJSON(jsonObject);
}
}