请问javabean中有一个list,能直接使用JSONObject的方法来进行转换,得到的依然有这种层次结构吗???不能应该怎么做!!!请帮忙解答
假设Contract下有一个LIst中装的Product
可以的,可以使用org.json包进行转换
[code="java"]
List products = new ArrayList();
Contract contract = new Contract();
contract.setProduct(products);
JSONObject obj = new JSONObject(contract);
[/code]
obj就是json对象了.
楼上写的有些问题。
用JSONObject的静态方法,fromObject
List stdList = new ArrayList();
stdList.add(new Student("1", "tom"));
stdList.add(new Student("2", "Jarry"));
stdList.add(new Student("3", "Test"));
Teacher tc = new Teacher(stdList);
JSONObject js = JSONObject.fromObject(tc);
System.out.println(js.toString());
测试了一下可以的。
{"studentList":[{"id":"1","name":"tom"},{"id":"2","name":"Jarry"},{"id":"3","name":"Test"}]}
建议楼主,查查相关资料,JSONObject的使用,并不止这么少。
百度或者谷歌一下,就这么难?
建议你直接使用google的gson库
new Gson().toJson(list);
jsonlib神马的都弱爆了,不如用jackson.
建议使用jackson进行转换。对list map 等对象转换很方便。
转为list:
public void readJson2List() {
String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
"{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
try {
List> list = objectMapper.readValue(json, List.class);
System.out.println(list.size());
for (int i = 0; i < list.size(); i++) {
Map map = list.get(i);
Set set = map.keySet();
for (Iterator it = set.iterator();it.hasNext();) {
String key = it.next();
System.out.println(key + ":" + map.get(key));
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
list 返转
List<AccountBean> list = new ArrayList<AccountBean>();
list.add(bean);
bean = new AccountBean();
bean.setId(2);
bean.setAddress("address2");
bean.setEmail("email2");
bean.setName("haha2");
list.add(bean);
System.out.println("jsonGenerator");
//list转换成JSON字符串
jsonGenerator.writeObject(list);
System.out.println();
System.out.println("ObjectMapper");
//用objectMapper直接返回list转换成的JSON字符串
System.out.println("1###" + objectMapper.writeValueAsString(list));
System.out.print("2###");
//objectMapper list转换成JSON字符串
objectMapper.writeValue(System.out, list);
什么jackson,gson 其实都是一样的,javabean都可以序列化成json规范 动手试一下就知道了。
什么都不说。强烈建议使用阿里的开源项目fastJSON来作为JSON与JAVA对象互转工具
public static T getObject(String jsonStr, Class clazz, Map clazzMap) {
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
return (T) JSONObject.toBean(jsonObject, clazz, clazzMap);
}
Map clazzMap = new HashMap();
clazzMap.put("product", Product.class);
Contract contract = getObject(jsonStr, Contract.class, clazzMap);
你直接用温少的FastJson吧,挺好用的。 开源的