在 Java 中解析 JSON 字符串有多种方式,以下是常用的几种实现方式,以及每种方式的步骤流程、示例代码和依赖坐标。
假设我们有以下 JSON 字符串作为示例:
{
"name": "John Doe",
"age": 30,
"isStudent": false,
"address": {
"street": "123 Main St",
"city": "Exampletown"
},
"hobbies": ["reading", "swimming", "gaming"]
}
这是一个简单的 JSON 处理库,可以在不使用任何 Maven 或 Gradle 依赖的情况下使用。
步骤流程:
示例代码:
import org.json.JSONObject;
public class JSONParsingUsingOrgJson {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John Doe\",\"age\":30,\"isStudent\":false,\"address\":{\"street\":\"123 Main St\",\"city\":\"Exampletown\"},\"hobbies\":[\"reading\",\"swimming\",\"gaming\"]}";
JSONObject jsonObject = new JSONObject(jsonString);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean isStudent = jsonObject.getBoolean("isStudent");
JSONObject address = jsonObject.getJSONObject("address");
JSONArray hobbies = jsonObject.getJSONArray("hobbies");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Is Student: " + isStudent);
System.out.println("Street: " + address.getString("street"));
System.out.println("City: " + address.getString("city"));
System.out.println("Hobbies: " + hobbies);
}
}
无需依赖,直接使用 org.json 库。
Jackson 是一个广泛使用的 JSON 处理库,可以通过 Maven 或 Gradle 添加依赖。
步骤流程:
readValue
方法将 JSON 字符串转换为 Java 对象。示例代码:
import com.fasterxml.jackson.databind.ObjectMapper;
public class JSONParsingUsingJackson {
public static void main(String[] args) throws Exception {
String jsonString = "{\"name\":\"John Doe\",\"age\":30,\"isStudent\":false,\"address\":{\"street\":\"123 Main St\",\"city\":\"Exampletown\"},\"hobbies\":[\"reading\",\"swimming\",\"gaming\"]}";
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(jsonString, Person.class);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("Is Student: " + person.isStudent());
System.out.println("Street: " + person.getAddress().getStreet());
System.out.println("City: " + person.getAddress().getCity());
System.out.println("Hobbies: " + person.getHobbies());
}
}
class Person {
private String name;
private int age;
private boolean isStudent;
private Address address;
private List<String> hobbies;
// Getters and setters
}
class Address {
private String street;
private String city;
// Getters and setters
}
Maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
Gradle:
implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
这些是解析 JSON 字符串的两种常用方式,每种方式都有其优势和适用场景。选择其中一种方式来解析 JSON 取决于项目的需求和个人偏好。