{"pid":"1","pinyin":"手机","pname":"shouji"}
[{"pid":"1","pinyin":"手机","pname":"shouji"},{"pid":"2","pinyin":"电脑","pname":"diannao"}]
{"desc":{"desc":"非常好"},"pid":"1","pinyin":"手机","pname":"shouji"}
[{"desc":{"desc":"非常好"},"pid":"1","pinyin":"手机","pname":"shouji"},{"desc":{"desc":"非常好"},"pid":"2","pinyin":"电脑","pname":"diannao"}]
即使换成Desc的集合,最终呈现也是ok的
3.将map集合转成JSON
也是ok的
只需要导一个包:flexjson-2.1.jar
方法只有一个
{"class":"cn.itcast.servlet.Product","pid":"1","pinyin":"手机","pname":"shouji"}
等desc为null时,会显示为null,不为null时,也会显示desc的class对象
{"class":"cn.itcast.servlet.Product","desc":{"class":"cn.itcast.servlet.Desc","desc":"和那帮"},"pid":"1","pinyin":"手机","pname":"shouji"}
如果map中分别存入三类数据
HashMap map = new HashMap();
//基本类型
map.put("total", 20);
//引用类型
Product pro = new Product("1", "shouji", "手机");
map.put("pro",pro);
//集合
ArrayList list = new ArrayList();
Product p1 = new Product("1", "shouji", "手机");
Product p2 = new Product("2", "diannao", "电脑");
list.add(p1);
list.add(p2);
map.put("rows",list);
JSONSerializer jsonSerializer = new JSONSerializer();
String json = jsonSerializer.serialize(map);
System.out.println(json);
最终显示:基本类型和对象都可以显示,但是集合无法显示
{"total":20,"pro":{"class":"cn.itcast.servlet.Product","desc":null,"pid":"1","pinyin":"手机","pname":"shouji"}}
我们需要这么做才行,添加一个include方法
String json = jsonSerializer.include(“rows”).serialize(map);