JAVA与JSON的序列化、反序列化

本文通过一个Java示例展示了如何使用JSON库将自定义Java对象转换为JSON字符串,并再将其转换回Java对象的过程。具体操作包括创建HashMap存储自定义对象、序列化为JSON字符串及反序列化为原始对象。

package com.linkage.app.memcache;

import java.util.HashMap;
import java.util.Map.Entry;

import net.sf.ezmorph.Morpher;
import net.sf.ezmorph.MorpherRegistry;
import net.sf.ezmorph.bean.BeanMorpher;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

import org.apache.taglibs.standard.lang.jpath.example.Person;

import com.linkage.app.vo.admin.ModuleRoleBean;

public class JsonTester {
    public static void main(String[] args) {
        HashMap<String, ModuleRoleBean> map = new HashMap<String, ModuleRoleBean>();

        ModuleRoleBean bean = new ModuleRoleBean();
        bean.setComments("fdsafsafsa");
        bean.setModuleId(323);
        bean.setModuleName("zhou");
        // bean.setStateDate(new Date(System.currentTimeMillis()));
        map.put("1", bean);
        map.put("32", bean);

        JSONObject jsonObject = JSONObject.fromObject(map);
        String json = jsonObject.toString();
        System.out.println(json);
        System.out.println("################");

        JSONObject fromObject = JSONObject.fromObject(json);
        HashMap<String, ModuleRoleBean> retVal = (HashMap<String, ModuleRoleBean>) JSONObject.toBean(fromObject,
                map.getClass());

        MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry();
        Morpher dynaMorpher = new BeanMorpher(ModuleRoleBean.class, morpherRegistry);
        morpherRegistry.registerMorpher(dynaMorpher);

        for (Entry<String, ModuleRoleBean> entry : retVal.entrySet()) {
            System.out.println("@@" + entry.getKey());
            // System.out.println(entry.getValue().getClass());
            System.out.println("@@" + entry.getValue());
            System.out.println("@@" + morpherRegistry.morph(ModuleRoleBean.class, entry.getValue()));
            System.out.println();
        }
    }
}

转载于:https://www.cnblogs.com/javafan/p/3832950.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值