使用json-lib将Java对象转SONObject,Java集合转JSONArray

来源:互联网 发布:win7旗舰版优化服务 编辑:程序博客网 时间:2024/06/06 17:30

解析用的json包

gradle 引用

net.sf.json-lib:json-lib:2.4:jdk15

待转换的java类

public class User implements Serializable {    private String name;    private List<Order> orders;    private Date createDate = new Date();    ...}public class Order implements Serializable {    private String sn;    private BigDecimal amount;    private Date createTime = new Date();    private Set<Item> items;    ...}public class Item implements Serializable {    private String pid;    private String pName;    ...}

数据初始化

@Beforepublic void init() {    try {        Item item = new Item();        item.setPid("pid_1");        item.setpName("pName");        Order order = new Order();        order.setAmount(new BigDecimal(3.4).setScale(2, BigDecimal.ROUND_HALF_DOWN));        order.setSn("ordersn_001");        order.setItems(Collections.singleton(item));        user = new User();        user.setName("akio");        user.setCreateDate(new Date());        user.setOrders(Collections.singletonList(order));        users = Collections.singletonList(user);    } catch (Exception e) {        e.printStackTrace();    }}

转换

@Testpublic void testObjectToJson() {    try {        JsonConfig jsonConfig = new JsonConfig();        //注册类中的属性名称转换        jsonConfig.registerJsonPropertyNameProcessor(User.class, new PropertyNameProcessor() {            @Override            public String processPropertyName(Class arg0, String arg1) {                // 处理User的属性,将user中的属性在json中转为大写                // 如果要处理Order的属性,需要重新注册一个PropertyNameProcessor                return arg1.toUpperCase();            }        });        //注册时间类型的格式转换        jsonConfig.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {            @Override            public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {                return DateFormatUtils.format((Date) arg1, "yyyy-MM-dd HH:mm:ss:SSS");            }            @Override            public Object processArrayValue(Object arg0, JsonConfig arg1) {                return null;            }        });        //注册Item类的转换,返回自定义的jsonObject        jsonConfig.registerJsonBeanProcessor(Item.class, new JsonBeanProcessor() {            @Override            public JSONObject processBean(Object arg0, JsonConfig arg1) {                Item u = (Item) arg0;                return new JSONObject().element("name_pid", u.getPid());            }        });        //定义java类的不需要被转换的属性所标记的注解类        //在java类中的getter方法中添加注解类@JsonIgnore后,在此处也做相应的添加,则转换后的json中不包含相应的属性        // jsonConfig.addIgnoreFieldAnnotation(JsonIgnore.class);        JSONObject json = JSONObject.fromObject(user, jsonConfig);        System.out.println(json.toString());        JSONArray array = JSONArray.fromObject(users, jsonConfig);        System.out.println(array.toString());    } catch (Exception e) {        e.printStackTrace();    }}
0 0