Java 组装json
已有 828 次阅读2019-9-25 11:06
|个人分类:Java
示例一:
想拼装出这样的json:content={"name":"李四","sex":"女","age":15}
这里需要使用到map的键值对
如果json里面既存在String类型也存在integer类型,那么此时的map的值的类型就是Object,如下
Map<String,Object> aa = new HashMap<>();
aa.put("name","李四");
aa.put("sex","女");
aa.put("age",15);
String content = JSONObject.toJSONString(aa);
System.out.println("content="+content);
==============================================================
如果想拼装出这样的json: content={"a1":"a1_value","a2":[{"b2":"b2_value","b1":"b1_value"}],"a3":123} json里面带数组
如下这么拼装:
Map<String,Object> mm= new HashMap<>();
Map<String,String> kk= new HashMap<>();
List<Map<String,String>> list = new ArrayList<>();
mm.put("a1","a1_value");
kk.put("b1","b1_value");
kk.put("b2","b2_value");
list.add(kk);
mm.put("a3",123);
mm.put("a2",list);
String content = JSONObject.toJSONString(mm);
System.out.println("content="+content);