java entity转js的json对象
前后端分离开发时,有时候从entity实体中复制字段到前端要一个一个替换比较麻烦写了一个批量替换的方法
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Java entity to json</title> </head> <body> <textarea rows="40" cols="80" id="str" onblur="convert()"> private Integer menuId; private Integer parentId; private Integer menuType; private String menuName; private String menuHost; private String menuUrl; private String menuIcon; private Integer sort; //OrderIndex private Integer isShowMenu; private Integer isShowSet; private String accessCodeIdStr; private String remark; private Integer isPublice; //one to one/many private List<User> userList=new ArrayList<User>();//user private List<Access> AccessList=new ArrayList<AccessList>(); //Access private Set<Message> MessageList=new HashSet<Message>();</textarea> <textarea rows="40" cols="80" id="str2"> </textarea> <input type="button" value="转换" onclick="convert()" /> <script> function convert(){ var str=document.getElementById("str").value; //console.log(str) //var strArr=str.split(/[(\r\n)\r\n]+/); var strArr=str.split(/[\n]/) console.log(strArr) var str2=""; for(var i=0;i<strArr.length;i++){ var lineStr=trimRight(trimLeft(strArr[i])); if(lineStr.indexOf("private")==0 || lineStr.indexOf("public")==0){ lineStr=lineStr.replace(";"," "); lineStr=lineStr.replace("="," "); console.log(lineStr) var lineArr=lineStr.split(" "); var fieldName=lineArr[2] console.log(fieldName+"--"+lineArr.length); if(lineStr.indexOf("new ")>0){ str2+=''+fieldName+':[],'; }else{ str2+=''+fieldName+':null,'; } if(lineArr[lineArr.length-1].indexOf("//")>-1){ str2+=lineArr[lineArr.length-1]; } str2+='\n'; }else{ str2+=''+lineStr+'\n'; } } document.getElementById("str2").value=str2; } convert(); //去掉左边的空白 function trimLeft(s){ if(s == null) { return ""; } var whitespace = new String(" \t\n\r"); var str = new String(s); if (whitespace.indexOf(str.charAt(0)) != -1) { var j=0, i = str.length; while (j < i && whitespace.indexOf(str.charAt(j)) != -1){ j++; } str = str.substring(j, i); } return str; } //去掉右边的空白 function trimRight(s){ if(s == null) return ""; var whitespace = new String(" \t\n\r"); var str = new String(s); if (whitespace.indexOf(str.charAt(str.length-1)) != -1){ var i = str.length - 1; while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){ i--; } str = str.substring(0, i+1); } return str; } </script> </body> </html>
效果如下
欢迎加入JAVA技术交流QQ群:179945282
欢迎加入ASP.NET(C#)交流QQ群:17534377