rt,lz是新手,对于此不知所措,,先谢谢大侠们了!
------解决方案--------------------
用现成的吧,json-lib
------解决方案--------------------
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonUtils {
public static String encodeList(Object[] objs) {
return encodeList(Arrays.asList(objs));
}
@SuppressWarnings("unchecked")
public static String encodeList(Collection objs) {
JSONArray list = new JSONArray();
if (objs == null
------解决方案--------------------
objs.size() == 0)
return list.toString();
for (Object ae : objs) {
list.add(ae);
}
return list.toString();
}
@SuppressWarnings("unchecked")
public static String encodeObject(Object obj) {
if (obj instanceof Collection)
return encodeList((Collection) obj);
JSONObject jo = JSONObject.fromObject(obj);
return jo.toString();
}
@SuppressWarnings("unchecked")
public static <T> List<T> decodeList(String str, Class<T> clazz) {
if (str == null
------解决方案--------------------
"".equals(str))
return null;
JSONArray obj = JSONArray.fromObject(str);
Object[] rts = obj.toArray();
List<T> result = new ArrayList<T>(rts.length);
for (int i = 0; i < rts.length; i++) {
Object jo = rts[i];
T ele = (T) JSONObject.toBean((JSONObject) jo, clazz);
result.add(ele);
}
return result;
}
@SuppressWarnings("unchecked")
public static <T> T decodeObject(String json, Class<T> clz) {
JSONObject jsonObject = JSONObject.fromObject(json);
T bean = (T) JSONObject.toBean(jsonObject, clz);
return bean;
}
public static void main(String[] args) {
DTO d = new DTO();
d.setName("dto");
Son realSone = new Son();
realSone.setName("father,son");
realSone.setSonName("son1");
realSone.setAge(1);
d.setRealSon(realSone);
Son realSone2 = new Son();
realSone.setName("father,son2");
realSone.setSonName("son2");
realSone.setAge(2);
d.setSon(realSone2);
List<Father> sonList = new ArrayList<Father>();
sonList.add(realSone);
sonList.add(realSone2);
d.setSonList(sonList);
String json=encodeObject(d);
System.out.println(encodeObject(d));
//JSONObject parseObject = JSON.parseObject(json);
JSONObject fromObject = JSONObject.fromObject(json);
Map<String, Class> classMap = new HashMap<String, Class>();
classMap.put("realSon", Son.class);
classMap.put("son", Son.class);
classMap.put("sonList", Father.class);
DTO newDto = (DTO) fromObject.toBean(fromObject, DTO.class, classMap);
System.out.println(newDto.getSonList().get(0).getName());
}
}