日期:2014-05-16 浏览次数:20497 次
classMap.put("user", User.class); jsonCfg.setClassMap(classMap);
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]}