1. 解析 JSON 字符串到 Java 对象
String jsonString = "{\"name\":\"John\",\"age\":30}";
JSONObject jsonObject = JSON.parseObject(jsonString);
String name = jsonObject.getString("name");
int age = jsonObject.getIntValue("age");
2. 将 Java 对象转换为 JSON 字符串
Person person = new Person("John", 30);
String jsonString = JSON.toJSONString(person);
System.out.println(jsonString); // 输出: {"name":"John","age":30}
3. 复杂对象的解析与转换
String jsonString = "{\"name\":\"John\",\"age\":30,\"address\":{\"city\":\"New York\",\"zipCode\":\"10001\"}}";
JSONObject jsonObject = JSON.parseObject(jsonString);
String name = jsonObject.getString("name");
int age = jsonObject.getIntValue("age");
JSONObject addressJson = jsonObject.getJSONObject("address");
String city = addressJson.getString("city");
String zipCode = addressJson.getString("zipCode");
4. JSON 数组的解析与转换
String jsonArrayString = "[{\"name\":\"John\",\"age\":30},{\"name\":\"Alice\",\"age\":25}]";
JSONArray jsonArray = JSON.parseArray(jsonArrayString);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
int age = jsonObject.getIntValue("age");
System.out.println("Name: " + name + ", Age: " + age);
}
5. 自定义序列化和反序列化规则
SerializeConfig config = new SerializeConfig();
config.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd"));
config.put(BigDecimal.class, BigDecimalCodec.instance);
JSON.toJSONString(object, config);