- 创建JSON对象:
// 使用Jackson库,可以使用ObjectMapper类来创建JSON对象。例如:
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode json = objectMapper.createObjectNode();
json.put("name", "John");
json.put("age", 25);
// 使用Gson库,可以使用JsonObject类来创建JSON对象。例如:
JsonObject json = new JsonObject();
json.addProperty("name", "John");
json.addProperty("age", 25);
- 解析JSON字符串:
// 使用Jackson库,可以使用ObjectMapper类的readTree方法来解析JSON字符串。例如:
String jsonString = "{\"name\":\"John\",\"age\":25}";
JsonNode jsonNode = objectMapper.readTree(jsonString);
String name = jsonNode.get("name").asText();
int age = jsonNode.get("age").asInt();
// 使用Gson库,可以使用JsonParser类的parse方法来解析JSON字符串。例如:
String jsonString = "{\"name\":\"John\",\"age\":25}";
JsonElement jsonElement = JsonParser.parseString(jsonString);
JsonObject json = jsonElement.getAsJsonObject();
String name = json.get("name").getAsString();
int age = json.get("age").getAsInt();
- 修改JSON对象:
// 使用Jackson库,可以使用ObjectNode类的各种方法来修改JSON对象。例如:
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode json = objectMapper.createObjectNode();
json.put("name", "John");
json.put("age", 25);
json.put("email", "john@example.com");
json.put("age", 26); // 修改age字段的值
json.remove("email"); // 删除email字段
// 使用Gson库,可以直接修改JsonObject对象的属性值。例如:
JsonObject json = new JsonObject();
json.addProperty("name", "John");
json.addProperty("age", 25);
json.addProperty("email", "john@example.com");
json.addProperty("age", 26); // 修改age字段的值
json.remove("email"); // 删除email字段
- 将JSON对象转换为字符串: