在 Java 中,将 JSON 字符串转换为 JSONObject
可以使用多种库,其中最常用的有 Jackson 和 Gson。下面是使用这两种库的示例代码。
使用 Jackson 库
- 添加 Jackson 依赖:
如果你使用 Maven,可以在
pom.xml
中添加以下依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
- 示例代码:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
public class JacksonExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
// 创建 ObjectMapper 实例
ObjectMapper objectMapper = new ObjectMapper();
try {
// 将 JSON 字符串转换为 JsonNode 对象
JsonNode jsonNode = objectMapper.readTree(jsonString);
// 访问 JSON 数据
String name = jsonNode.get("name").asText();
int age = jsonNode.get("age").asInt();
String city = jsonNode.get("city").asText();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用 Gson 库
- 添加 Gson 依赖:
如果你使用 Maven,可以在
pom.xml
中添加以下依赖:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.8</version>
</dependency>
- 示例代码:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class GsonExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
// 创建 JsonParser 实例
JsonParser jsonParser = new JsonParser();
try {
// 将 JSON 字符串转换为 JsonObject 对象
JsonObject jsonObject = jsonParser.parse(jsonString).getAsJsonObject();
// 访问 JSON 数据
String name = jsonObject.get("name").getAsString();
int age = jsonObject.get("age").getAsInt();
String city = jsonObject.get("city").getAsString();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用 org.json 库
- 添加 org.json 依赖:
如果你使用 Maven,可以在
pom.xml
中添加以下依赖:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
- 示例代码:
import org.json.JSONObject;
public class OrgJsonExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
try {
// 将 JSON 字符串转换为 JSONObject 对象
JSONObject jsonObject = new JSONObject(jsonString);
// 访问 JSON 数据
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String city = jsonObject.getString("city");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
} catch (Exception e) {
e.printStackTrace();
}
}
}
总结
- Jackson:功能强大,支持复杂的 JSON 处理,广泛用于企业级应用。
- Gson:简单易用,适合轻量级应用。
- org.json:标准库,功能基本满足日常需求。
选择哪种库取决于具体需求和项目复杂度。