转为JSON串的两种方法:
1.JSONObject j = new JSONObject j.put("",""); j.toString();
2.Map<String,Object> j = new HashMap<String,Object>();
j.put("",""); new JSONObject(j).toString();
方法跟逻辑与JSONObject类似
new JSONObject(new HashMap<String, Object>().put("name","王小二"));
Map构建JSON
方式二:使用Map构建JSON(通过HashMap构建JSON)
【a】:创建Map集合,通过Map的put方法存储数据。
【b】创建JSONObject对象并把Map对象作为参数。
构建JSON的几种方式:
① JSONObject jo = new JSONObject();
插入数据:jo.put(key , value);
输出:jo.toString();
② 使用HashMap构建
Map<String , Object> jm = new HashMap<String , Object>();
插入数据:jm.put(key , value);
输出:new JSONObject( jm ).toString();
JSONObject创建json数据 new JSONObejct,put("name",value).toString(); HashMap创建json数据 new HashMap.put("name",value) new JSONObejct(HashMap).toString()
用HashMap构建JSON格式数据比Java对象更为方便
new JSONObject(一个map接口的对象)
用 Map来构建Json对象
new JSONObject(map);
JSONObject对象通过map来构建json格式数据
构建JSON对象主要通过2种方法:
JsonObject duixiangming=new JsonObject();
Map<String ,Object> duixingming=new Map<String Object>;
当使用Map这种方法构建对象时,如果要输出,则需要进行转化。
使用Map实现Json private static void createJsonByMap(){ Map<String, Object> wangxiaoer=new HashMap<String,Object>(); Object nullObj = null; wangxiaoer.put("name", "王小二"); wangxiaoer.put("age", 25.2); wangxiaoer.put("birthday", "1990-01-01"); wangxiaoer.put("school", "蓝翔"); wangxiaoer.put("major", new String[] { "理发", "挖掘机" }); wangxiaoer.put("has_girlfriend", false); wangxiaoer.put("car", nullObj); wangxiaoer.put("house", nullObj); wangxiaoer.put("comment", "这是一个注释"); System.out.println(new JSONObject(wangxiaoer).toString()); }
通过map构建json
利用map 和jsonobject创建json