- 使用Jackson库解析JSON:
在Maven项目中,在pom.xml中添加以下依赖:
<!-- Jackson Core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.5</version>
</dependency>
<!-- Jackson Databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.5</version>
</dependency>
代码示例:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonParserUsingJackson {
public static void main(String[] args) {
String jsonString = "{\"name\": \"John\", \"age\": 30, \"email\": \"john@example.com\"}";
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);
String name = jsonNode.get("name").asText();
int age = jsonNode.get("age").asInt();
String email = jsonNode.get("email").asText();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Email: " + email);
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 使用Gson库解析JSON:
添加以下依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
示例代码:
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class JsonParserUsingGson {
public static void main(String[] args) {
String jsonString = "{\"name\": \"John\", \"age\": 30, \"email\": \"john@example.com\"}";
try {
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
String name = jsonObject.get("name").getAsString();
int age = jsonObject.get("age").getAsInt();
String email = jsonObject.get("email").getAsString();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Email: " + email);
} catch (Exception e) {
e.printStackTrace();
}
}
}