依赖第三方库 phprpc
序列化成php格式的字符串很简单,直接调用 org.phprpc.util.PHPSerializer.serializer方法就行,有问题的是反序列化php格式的字符串为List或Map对象时,得到的是个
AssocArray对象,需要写方法进行转换。通过下面这个方法可以实现转为java对象。
public static Object phpUnserialize(String s) { Object rtn = null; try { AssocArray aa = (AssocArray) ps.unserialize(s.getBytes(CharEncoding.UTF_8)); rtn = transfer(aa); }catch (Exception e){ e.printStackTrace(); } return rtn; } private static Object transfer(Object o){ Object rtn = null; if(o instanceof AssocArray) { AssocArray aa = (AssocArray) o; List l = aa.toArrayList(); if(l==null || l.size()==0){ Map m = aa.toHashMap(); rtn = transfer(m); }else{ rtn = transfer(l); } }else if(o instanceof Map){ Map m = (Map<?, ?>) o; for(Object key:m.keySet()){ Object v = m.get(key); if(v instanceof AssocArray){ v = transfer(v); m.put(key,v); } else if (v instanceof byte[]) { m.put(key,new String(((byte[])v))); } } rtn = m; } else if (o instanceof List) { List l = (List) o; List newL = new ArrayList(); for(int i=0;i<l.size();i++){ Object o1 = l.get(i); o1 = transfer(o1); newL.add(o1); } rtn = newL; } else if(o instanceof byte[]){ rtn = new String(((byte[])o)); }else { rtn = o; } return rtn; }
标签:AssocArray,Object,java,rtn,List,序列化,php From: https://www.cnblogs.com/zahngkai/p/17415561.html