JSON字符串和java对象的互转【json-lib】

1. 什么是 json-lib

json-lib 是一个老牌 Java JSON 处理库,可以方便地在 Java 对象和 JSON 字符串之间互转。

虽然现在更流行的库有 Jackson、Gson,但 json-lib 依然在一些遗留项目中使用。


2. 引入依赖

Maven 依赖

xml 复制代码
<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>
php
165 Bytes
© 菜鸟-创作你的创作

注意

json-lib 依赖以下库,需确保也引入:

  • commons-lang
  • commons-beanutils
  • commons-collections
  • commons-logging

3. 核心类

  • JSONObject --- 代表 JSON 对象
  • JSONArray --- 代表 JSON 数组
  • JsonConfig --- 配置序列化/反序列化行为

4. Java 对象转 JSON 字符串

示例代码

假设有个简单的 Java 类:

typescript 复制代码
public class User {
    private String name;
    private int age;
    // getter/setter
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}
php
285 Bytes
© 菜鸟-创作你的创作

转换示例:

typescript 复制代码
import net.sf.json.JSONObject;
public class JsonLibDemo {
    public static void main(String[] args) {
        User user = new User();
        user.setName("小明");
        user.setAge(18);
        JSONObject json = JSONObject.fromObject(user);
        String jsonString = json.toString();
        System.out.println(jsonString);
    }
}
php
338 Bytes
© 菜鸟-创作你的创作

输出:

json 复制代码
{"age":18,"name":"小明"}
php
22 Bytes
© 菜鸟-创作你的创作

5. JSON 字符串转 Java 对象

typescript 复制代码
import net.sf.json.JSONObject;
public class JsonLibDemo {
    public static void main(String[] args) {
        String jsonString = "{"age":18,"name":"小明"}";
        JSONObject json = JSONObject.fromObject(jsonString);
        User user = (User) JSONObject.toBean(json, User.class);
        System.out.println(user.getName()); // 小明
        System.out.println(user.getAge());  // 18
    }
}
php
398 Bytes
© 菜鸟-创作你的创作

6. 处理集合类

Java 集合转 JSONArray

ini 复制代码
import net.sf.json.JSONArray;
import java.util.ArrayList;
import java.util.List;
List<User> userList = new ArrayList<>();
userList.add(user1);
userList.add(user2);
JSONArray jsonArray = JSONArray.fromObject(userList);
System.out.println(jsonArray.toString());
php
261 Bytes
© 菜鸟-创作你的创作

JSONArray 转 List

ini 复制代码
JSONArray jsonArray = JSONArray.fromObject(jsonString);
List<User> users = (List<User>) JSONArray.toCollection(jsonArray, User.class);
php
134 Bytes
© 菜鸟-创作你的创作

7. 注意事项

  • 日期处理
    默认日期格式会被序列化为时间戳,可以使用 JsonConfig 自定义日期格式。
  • 循环引用
    如果对象间存在循环引用,json-lib 可能会报错。
  • 性能
    json-lib 较老,性能和兼容性不如 Jackson 和 Gson。

8. 代码示例(含日期格式化)

typescript 复制代码
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import java.text.SimpleDateFormat;
import java.util.Date;
public class JsonLibDateDemo {
    public static void main(String[] args) {
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        jsonConfig.registerJsonValueProcessor(Date.class, (value, jsonConfig1) -> {
            if (value == null) return "";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(value);
        });
        MyBean bean = new MyBean();
        bean.setDate(new Date());
        JSONObject json = JSONObject.fromObject(bean, jsonConfig);
        System.out.println(json.toString());
    }
}
class MyBean {
    private Date date;
    public Date getDate() { return date; }
    public void setDate(Date date) { this.date = date; }
}
php
962 Bytes
© 菜鸟-创作你的创作

www.52runoob.com/archives/55...

相关推荐
bobz96516 分钟前
QT 中的三种基本UI类型:Main Window | Widget | Dialog
后端
zhoupenghui16827 分钟前
golang实现支持100万个并发连接(例如,HTTP长连接或WebSocket连接)系统架构设计详解
开发语言·后端·websocket·golang·系统架构·echo·100万并发
咸甜适中42 分钟前
Rust语言序列化和反序列化vec<u8>,serde库Serialize, Deserialize,bincode库(2025年最新解决方案详细使用)
开发语言·后端·rust
JiaHao汤2 小时前
Java 虚拟机之双亲委派机制
java·jvm·后端
哈基米喜欢哈哈哈2 小时前
Uber的MySQL实践(一)——学习笔记
数据库·笔记·后端·mysql
姑苏洛言3 小时前
扫码点餐小程序产品需求分析与功能梳理
前端·javascript·后端
Java技术小馆3 小时前
PromptPilot打造高效AI提示词
java·后端·面试
陈陈陈同学243 小时前
Vercel迁移到Dokploy自部署,每月立省20刀
后端·node.js
倔强的皮皮虾4 小时前
sharding proxy 实战读写分离,分库分表
后端
ONE_Gua4 小时前
魔改chromium源码——解除 iframe 的同源策略
前端·后端·浏览器