日期:2014-05-16  浏览次数:20497 次

jsonlib反序列化map时指定map中对象的类型
一个java对象中的某个固定属性反序列化时指定它的类型很简单:
classMap.put("user", User.class);
jsonCfg.setClassMap(classMap);

如果是一个map对象,map中的key是不确定的,如何指定它的value类型呢?
使用“.*”匹配map中的所有key,如下所示
classMap.put(".*", User.class);
jsonCfg.setClassMap(classMap);

示例如下:
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;

public class Json2MapTest {
    public static final Log log = LogFactory.getLog(Json2MapTest.class);

    @Test
    public void testJson2Map() {
        Map<String, User> map = new HashMap<String, User>();
        map.put("user0", new User(0,"user0","user0@apusic.com"));
        map.put("user1", new User(1,"user1","user1@apusic.com"));
        String jsonString = JSONObject.fromObject(map).toString();
        JSONObject jsonObj = JSONObject.fromObject(jsonString);
        JsonConfig jsonCfg = new JsonConfig();
        jsonCfg.setRootClass(Map.class);
        Map<String,Class> classMap = new HashMap<String, Class>();
        classMap.put(".*", User.class);
        jsonCfg.setClassMap(classMap);
        Map<String,User> deserializedMap = (Map<String, User>) JSONObject.toBean(jsonObj,new HashMap(),jsonCfg);
        log.debug(deserializedMap.toString());
    }

}


输出结果:
{user0=User [email=user0@apusic.com, id=0, name=user0], user1=User [email=user1@apusic.com, id=1, name=user1]}