集合转json对象时,去除不想要的字段,替换自己想要的字段

1: 去除不想要的字段

List stu= new Student();
  //通过JsonConfig的对象,来去除,json数据中不要的字段
 JsonConfig cfg = new JsonConfig();
 cfg.setExcludes(new String[]{"a","b","c","d"});
             
  //将集合转换成json
  JSONArray ja=JSONArray.fromObject(stu,cfg);

2:替换自己不想要的字段

List phone = formService.getPhone();

JSONArray fromObject = JSONArray.fromObject(phone);
        JSONArray list = new JSONArray();
        JSONObject json = null;
        int len=fromObject.size();
        for(int i=0;i            
            json = fromObject.optJSONObject(i);
           
           //替换
         
            json.put("tel", json.optString("exttel"));

//剔除
            json.discard("exttel");
            json.discard("depart1Name");
            json.discard("cdate");
            list.add(json);
        }

你可能感兴趣的:(java)