- 浏览: 526106 次
文章分类
最新评论
-
Mr.TianShu:
优化一下
public static void te ...
输出101~200内的质数 -
Mr.TianShu:
1既不是质数也不是合数此方法判断0-100就会发生错误错误的写 ...
输出101~200内的质数 -
li_yue_qing12:
求代码啊!!!!
[项目实战] ibatis +spring+struts2+jquery.autocomplete实现产品自动补全功能(一) -
遥远的救世主:
...
多线程编程 高级主题(一)
自己编写的一个Json工具类,实现了反射将整个Object转换为Json对象的功能,支持Hibernate的延迟加载对象[修订081217]
最后更新:09-02-08
bug fix:支持了Hibernate one-to-many映射到List的处理
由于Json自己的String转换有问题,无法正确的转换中文为uxxxx的字符,因此改用DWR包内的JavascriptUtil处理String类型。可以直接引用,还可以拆离出来,因为仅是一个转换工具类,跟DWR的没有依赖关系。这样就可以采用ISO-8859-1编码来传递所有UNICODE了。
代码:
- packagecom.aherp.framework.util;
- importorg.json.JSONString;
- publicclassJSONStringObjectimplementsJSONString{
- privateStringjsonString=null;
- publicJSONStringObject(StringjsonString){
- this.jsonString=jsonString;
- }
- @Override
- publicStringtoString(){
- returnjsonString;
- }
- publicStringtoJSONString(){
- returnjsonString;
- }
- }
- packagecom.aherp.framework.util;
- importjava.lang.reflect.Array;
- importjava.lang.reflect.Method;
- importjava.util.Calendar;
- importjava.util.Date;
- importjava.util.Map;
- importjava.util.Map.Entry;
- importorg.json.JSONArray;
- importorg.json.JSONException;
- importorg.json.JSONObject;
- importorg.json.JSONString;
- /**
- *JSON工具类,反射的方式转换整个对象
- *@authorJimWu
- *
- */
- publicclassJSONUtil{
- privatestaticJSONUtilinstance=null;
- publicJSONUtil(){}
- /**
- *代理类是否输出的检查,返回true则允许继续转换
- *@parambean
- *@return是否允许继续转换
- */
- protectedbooleancanProxyOutput(Objectbean){
- returntrue;
- }
- /**
- *代理类时做的检查.返回应该检查的对象.
- *@parambean
- *@return实际获取的对象
- */
- protectedObjectproxyConvert(Objectbean){
- returnbean;
- }
- staticpublicStringtoJSONString(Objectobj)throwsJSONException{
- returntoJSONString(obj,false);
- }
- staticpublicStringtoJSONString(Objectobj,booleanuseClassConvert)throwsJSONException{
- if(instance==null)
- instance=newJSONUtil();
- returninstance.getJSONObject(obj,useClassConvert).toString();
- }
- @SuppressWarnings("unchecked")
- privateStringgetJSONArray(ObjectarrayObj,booleanuseClassConvert)throwsJSONException{
- if(arrayObj==null)
- return"null";
- arrayObj=proxyConvert(arrayObj);
- JSONArrayjSONArray=newJSONArray();
- if(arrayObjinstanceofIterable){
- for(ObjectrowObj:((Iterable)arrayObj)){
- if(canProxyOutput(rowObj)){
- if(rowObj==null)
- jSONArray.put(newJSONStringObject(null));
- elseif(rowObj.getClass().isArray()||rowObjinstanceofIterable)
- jSONArray.put(getJSONArray(rowObj,useClassConvert));
- else
- jSONArray.put(getJSONObject(rowObj,useClassConvert));
- }
- }
- }
- if(arrayObj.getClass().isArray()){
- intarrayLength=Array.getLength(arrayObj);
- for(inti=0;i<arrayLength;i++){
- ObjectrowObj=Array.get(arrayObj,i);
- if(canProxyOutput(rowObj)){
- if(rowObj==null)
- jSONArray.put(newJSONStringObject(null));
- elseif(rowObj.getClass().isArray()||rowObjinstanceofIterable)
- jSONArray.put(getJSONArray(rowObj,useClassConvert));
- else
- jSONArray.put(getJSONObject(rowObj,useClassConvert));
- }
- }
- }
- returnjSONArray.toString();
- }
- @SuppressWarnings("unchecked")
- JSONStringObjectgetJSONObject(Objectvalue,booleanuseClassConvert)throwsJSONException{
- //处理原始类型
- if(value==null){
- returnnewJSONStringObject("null");
- }
- value=proxyConvert(value);
- if(valueinstanceofJSONString){
- Objecto;
- try{
- o=((JSONString)value).toJSONString();
- }catch(Exceptione){
- thrownewJSONException(e);
- }
- thrownewJSONException("BadvaluefromtoJSONString:"+o);
- }
- if(valueinstanceofNumber){
- returnnewJSONStringObject(JSONObject.numberToString((Number)value));
- }
- if(valueinstanceofBoolean||valueinstanceofJSONObject||
- valueinstanceofJSONArray){
- returnnewJSONStringObject(value.toString());
- }
- if(valueinstanceofString)
- returnnewJSONStringObject('"'+JavascriptUtil.escapeJavaScript(value.toString())+'"');
- if(valueinstanceofMap){
- JSONObjectjSONObject=newJSONObject();
- for(ObjectrowObj:((Map)value).entrySet()){
- Entryentry=(Entry)rowObj;
- ObjectvalueObj=entry.getValue();
- if(canProxyOutput(valueObj))
- jSONObject.put(entry.getKey().toString(),getJSONObject(valueObj,useClassConvert));
- }
- returnnewJSONStringObject(jSONObject.toString());
- }
- if(valueinstanceofDate){
- Calendarcalendar=Calendar.getInstance();
- calendar.setTime(calendar.getTime());
- StringBuildersb=newStringBuilder("newDate(");
- sb.append(calendar.get(Calendar.YEAR));
- sb.append(",");
- sb.append(calendar.get(Calendar.MONTH));
- sb.append(",");
- sb.append(calendar.get(Calendar.DAY_OF_MONTH));
- sb.append(",");
- sb.append(calendar.get(Calendar.HOUR_OF_DAY));
- sb.append(",");
- sb.append(calendar.get(Calendar.MINUTE));
- sb.append(",");
- sb.append(calendar.get(Calendar.SECOND));
- sb.append(")");
- returnnewJSONStringObject(sb.toString());
- }
- //class
- if(valueinstanceofClass)
- returnnewJSONStringObject(JavascriptUtil.escapeJavaScript(((Class)value).getSimpleName()));
- //数组
- if(valueinstanceofIterable||value.getClass().isArray()){
- returnnewJSONStringObject(getJSONArray(proxyConvert(value),useClassConvert));
- }
- returnreflectObject(value,useClassConvert);
- }
- @SuppressWarnings("unchecked")
- privateJSONStringObjectreflectObject(Objectbean,booleanuseClassConvert){
- JSONObjectjSONObject=newJSONObject();
- Classklass=bean.getClass();
- for(Methodmethod:klass.getMethods()){
- try{
- Stringname=method.getName();
- Stringkey="";
- if(name.startsWith("get")){
- key=name.substring(3);
- }elseif(name.startsWith("is")){
- key=name.substring(2);
- }
- if(key.length()>0&
- Character.isUpperCase(key.charAt(0))&
- method.getParameterTypes().length==0){
- if(key.length()==1){
- key=key.toLowerCase();
- }elseif(!Character.isUpperCase(key.charAt(1))){
- key=key.substring(0,1).toLowerCase()+
- key.substring(1);
- }
- ObjectelementObj=method.invoke(bean);
- if(!useClassConvert&&elementObjinstanceofClass)
- continue;
- if(canProxyOutput(elementObj))
- jSONObject.put(key,getJSONObject(elementObj,useClassConvert));
- }
- }catch(Exceptione){
- /*forgetaboutit*/
- }
- }
- returnnewJSONStringObject(jSONObject.toString());
- }
- }
调用测试程序
importjava.util.HashMap;
importjava.util.List;
publicclassAObj...{
privateintii=7;
privatebooleanbb=true;
privateStringss="你好";
privateListaList=newArrayList();
publicAObj()...{
aList.add("hello");
aList.add(false);
aList.add(newBObj());
aList.add(newHashMap());
}
publicbooleanisBb()...{
returnbb;
}
publicvoidsetBb(booleanbb)...{
this.bb=bb;
}
publicintgetIi()...{
returnii;
}
publicvoidsetIi(intii)...{
this.ii=ii;
}
publicStringgetSs()...{
returnss;
}
publicvoidsetSs(Stringss)...{
this.ss=ss;
}
publicListgetAList()...{
returnaList;
}
publicvoidsetAList(Listlist)...{
aList=list;
}
}
importjava.util.HashMap;
publicclassBObj...{
privateHashMapinnerhm=newHashMap();
publicBObj()...{
doubledd=7.4354;
innerhm.put("gigi","高兴");
innerhm.put("sina",newBigDecimal(dd));
}
publicHashMapgetInnerhm()...{
returninnerhm;
}
publicvoidsetInnerhm(HashMapinnerhm)...{
this.innerhm=innerhm;
}
}
publicclassCObjextendsAObj...{
privateObject[]oarray=newObject[]...{352,false,"kick"};
publicObject[]getOarray()...{
returnoarray;
}
publicvoidsetOarray(Object[]oarray)...{
this.oarray=oarray;
}
}
importcom.aherp.framework.util.JSONUtil;
publicclassTest...{
publicstaticvoidmain(String[]args)throwsJSONException...{
CObjcObj=newCObj();
System.out.println(JSONUtil.toJSONString(cObj));
}
}
输出:
{"AList":["hello",false,{"innerhm":{"gigi":"/u9AD8/u5174","sina":7.4353999999999995651478457148186862468719482421875}},{}],"ii":7,"oarray":[352,false,"kick"],"ss":"/u4F60/u597D","bb":true}
如果需要支持Hibernate,那么必须弄清其机制。Hibernate采用CGLIB对VO对象进行字节码增加,实际机制就是使用一个原类型的proxy子类,其子类实现了HibernateProxy接口。其接口有一个isUninitialized的判断方法,用来判断该代理类是否已经初始化(还记得在事务外使用延迟加载的对象会抛no Session的错误吗,正是由于实际使用的对象已经变成原来类的子类proxy了)。而对于one-to-many映射时,很难判断对象只加载一次,因此为了避免递归调用死循环,忽略了Hibernate的one-to-many集合的递归反射。其原理和many-to-one一样,也是一个子类化的proxy,具有PersistentSet的接口。
因此,支持Hibernate的JSONUtil如下:
- packagecom.aherp.framework.util;
- importorg.hibernate.collection.PersistentSet;
- importorg.hibernate.proxy.HibernateProxy;
- importorg.hibernate.proxy.LazyInitializer;
- importorg.json.JSONException;
- /**
- *支持Hibernate的JSONUtil.
- *自动检测是否已经代理加载,如果未加载,则将对象仅加载为OID
- *@authorJimWu
- *
- */
- publicclassHiJSONUtilextendsJSONUtil{
- privatestaticHiJSONUtilinstance=null;
- staticpublicStringtoJSONString(Objectobj)throwsJSONException{
- returntoJSONString(obj,false);
- }
- staticpublicStringtoJSONString(Objectobj,booleanuseClassConvert)throwsJSONException{
- if(instance==null)
- instance=newHiJSONUtil();
- returninstance.getJSONObject(obj,useClassConvert).toString();
- }
- @Override
- protectedObjectproxyConvert(Objectbean){
- if(beaninstanceofHibernateProxy){
- LazyInitializerlazyInitializer=((HibernateProxy)bean).getHibernateLazyInitializer();
- if(lazyInitializer.isUninitialized()){
- returnlazyInitializer.getIdentifier();
- }else
- returnlazyInitializer.getImplementation();
- }
- if(beaninstanceofPersistentSet || bean instanceof PersistentList){
- returnnewString[]{};//忽略hibernateone-to-many
- }
- returnbean;
- }
- @Override
- protectedbooleancanProxyOutput(Objectbean){
- return!(bean!=null&&(beaninstanceofPersistentSet || bean instanceof PersistentList));
- }
- }
- ;
但是这样还是有个问题,当one-to-one具备双向映射关系时,会陷入调用递归死循环。因此避免这样的情况。
将本人修改过的JavaScriptUtil也附上
- /*
- *Copyright2005JoeWalker
- *
- *LicensedundertheApacheLicense,Version2.0(the"License");
- *youmaynotusethisfileexceptincompliancewiththeLicense.
- *YoumayobtainacopyoftheLicenseat
- *
- *http://www.apache.org/licenses/LICENSE-2.0
- *
- *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
- *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
- *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
- *SeetheLicenseforthespecificlanguagegoverningpermissionsand
- *limitationsundertheLicense.
- */
- packagecom.aherp.framework.util;
- importjava.io.BufferedReader;
- importjava.io.IOException;
- importjava.io.StringReader;
- importjava.util.Arrays;
- importjava.util.Locale;
- importjava.util.SortedSet;
- importjava.util.TreeSet;
- importorg.apache.commons.logging.Log;
- importorg.apache.commons.logging.LogFactory;
- /**
- *VariousJavascriptcodeutilities.
- *Theescapeclassesweretakenfromjakarta-commons-langwhichinturnborrowed
- *fromTurbineandotherprojects.Thelistofauthorsbelowisalmostcertainly
- *fartoolong,butI'mnotsurewhoreallywrotethesemethods.
- *@authorJoeWalker[joeatgetaheaddotltddotuk]
- *@authorApacheJakartaTurbine
- *@authorGenerationJavaCorelibrary
- *@authorPurpleTechnology
- *@author<ahref="mailto:bayard@generationjava.com">HenriYandell</a>
- *@author<ahref="mailto:alex@purpletech.com">AlexanderDayChaffee</a>
- *@author<ahref="mailto:cybertiger@cyberiantiger.org">AntonyRiley</a>
- *@authorHelgeTesgaard
- *@author<ahref="sean@boohai.com">SeanBrown</a>
- *@author<ahref="mailto:ggregory@seagullsw.com">GaryGregory</a>
- *@authorPhilSteitz
- *@authorPeteGieser
- */
- @SuppressWarnings("unchecked")
- publicclassJavascriptUtil
- {
- /**
- *Flagforuseinjavascriptcompression:Removesinglelinecomments.
- *ForeaseofuseyoumaywishtouseoneoftheLEVEL_*compressionlevels.
- *@noinspectionPointlessBitwiseExpression
- */
- publicstaticfinalintCOMPRESS_STRIP_SL_COMMENTS=1<<0;
- /**
- *Flagforuseinjavascriptcompression:Removemultilinecomments.
- *ForeaseofuseyoumaywishtouseoneoftheLEVEL_*compressionlevels.
- */
- publicstaticfinalintCOMPRESS_STRIP_ML_COMMENTS=1<<1;
- /**
- *Flagforuseinjavascriptcompression:Removewhitespaceatthestartandendofaline.
- *ForeaseofuseyoumaywishtouseoneoftheLEVEL_*compressionlevels.
- */
- publicstaticfinalintCOMPRESS_TRIM_LINES=1<<2;
- /**
- *Flagforuseinjavascriptcompression:Removeblanklines.
- *Thisoptionwillmakethejavascripthardertodebugbecauselinenumberreferences
- *arelikelybealtered.
- *ForeaseofuseyoumaywishtouseoneoftheLEVEL_*compressionlevels.
- */
- publicstaticfinalintCOMPRESS_STRIP_BLANKLINES=1<<3;
- /**
- *Flagforuseinjavascriptcompression:Shrinkvariablenames.
- *Thisoptioniscurrentlyun-implemented.
- *ForeaseofuseyoumaywishtouseoneoftheLEVEL_*compressionlevels.
- */
- publicstaticfinalintCOMPRESS_SHRINK_VARS=1<<4;
- /**
- *Flagforuseinjavascriptcompression:Removealllinesendings.
- *Warning:Javascriptcanaddsemi-colonsinforyou.Ifyoumakeuseofthisfeature
- *thenremovingnewlinesmaywellbreak.
- *ForeaseofuseyoumaywishtouseoneoftheLEVEL_*compressionlevels.
- */
- publicstaticfinalintCOMPRESS_REMOVE_NEWLINES=1<<5;
- /**
- *Compressionlevelthatleavesthesourceun-touched.
- */
- publicstaticfinalintLEVEL_NONE=0;
- /**
- *Basiccompressionthatleavesthesourcefullydebuggable.
- *Thisincludesremovingallcommentsandextraneouswhitespace.
- */
- publicstaticfinalintLEVEL_DEBUGGABLE=COMPRESS_STRIP_SL_COMMENTS|COMPRESS_STRIP_ML_COMMENTS|COMPRESS_TRIM_LINES;
- /**
- *Normalcompressionmakesallchangesthatwillworkforgenericjavascript.
- *Thisaddsvariablenamecompressionandblanklineremovalinadditiontothe
- *compressionsdonebyLEVEL_DEBUGGABLE.
- */
- publicstaticfinalintLEVEL_NORMAL=LEVEL_DEBUGGABLE|COMPRESS_STRIP_BLANKLINES|COMPRESS_SHRINK_VARS;
- /**
- *LEVEL_ULTRAperformsadditionalcompressionthatmakessomeassumptionsaboutthe
- *styleofjavascript.
- *Specificallyitassumesthatyouarenotusingjavascriptsabilitytoinferwherethe;
- *shouldgo.
- */
- publicstaticfinalintLEVEL_ULTRA=LEVEL_NORMAL|COMPRESS_REMOVE_NEWLINES;
- /**
- *Compressthesourcecodebyremovingjavastylecommentsandremoving
- *leadingandtrailingspaces.
- *@paramtextThejavascript(orjava)programtocompress
- *@paramlevelThecompressionlevel-seeLEVEL_*andCOMPRESS_*constants.
- *@returnThecompressedversion
- */
- publicstaticStringcompress(Stringtext,intlevel)
- {
- Stringreply=text;
- //Firstwestripmultilinecomments.Ithinkthisisimportant:
- if((level&COMPRESS_STRIP_ML_COMMENTS)!=0)
- {
- reply=stripMultiLineComments(text);
- }
- if((level&COMPRESS_STRIP_SL_COMMENTS)!=0)
- {
- reply=stripSingleLineComments(reply);
- }
- if((level&COMPRESS_TRIM_LINES)!=0)
- {
- reply=trimLines(reply);
- }
- if((level&COMPRESS_STRIP_BLANKLINES)!=0)
- {
- reply=stripBlankLines(reply);
- }
- if((level&COMPRESS_SHRINK_VARS)!=0)
- {
- reply=shrinkVariableNames(reply);
- }
- if((level&COMPRESS_REMOVE_NEWLINES)!=0)
- {
- reply=stripNewlines(reply);
- }
- returnreply;
- }
- /**
- *Removeanyleadingortrailingspacesfromalineofcode.
- *Thisfunctioncouldbeimprovedbymakingitstripunnecessarydouble
- *spaces,butsincewewouldneedtoleavedoublespacesinsidestrings
- *thisisnotsimpleandsincethebenefitissmall,we'llleaveitfornow
- *@paramtextThejavascriptprogramtostripspacesfrom.
- *@returnThestrippedprogram
- */
- publicstaticStringtrimLines(Stringtext)
- {
- if(text==null)
- {
- returnnull;
- }
- try
- {
- StringBufferoutput=newStringBuffer();
- //Firstwestripmultilinecomments.Ithinkthisisimportant:
- BufferedReaderin=newBufferedReader(newStringReader(text));
- while(true)
- {
- Stringline=in.readLine();
- if(line==null)
- {
- break;
- }
- output.append(line.trim());
- output.append('/n');
- }
- returnoutput.toString();
- }
- catch(IOExceptionex)
- {
- log.error("IOExecptionunexpected.",ex);
- thrownewIllegalArgumentException("IOExecptionunexpected.");
- }
- }
- /**
- *Removeallthesingle-linecommentsfromablockoftext
- *@paramtextThetexttoremovesingle-linecommentsfrom
- *@returnThesingle-linecommentfreetext
- */
- publicstaticStringstripSingleLineComments(Stringtext)
- {
- if(text==null)
- {
- returnnull;
- }
- try
- {
- StringBufferoutput=newStringBuffer();
- BufferedReaderin=newBufferedReader(newStringReader(text));
- while(true)
- {
- Stringline=in.readLine();
- if(line==null)
- {
- break;
- }
- //Skip@DWRcomments
- if(line.indexOf(COMMENT_RETAIN)==-1)
- {
- intcstart=line.indexOf(COMMENT_SL_START);
- if(cstart>=0)
- {
- line=line.substring(0,cstart);
- }
- }
- output.append(line);
- output.append('/n');
- }
- returnoutput.toString();
- }
- catch(IOExceptionex)
- {
- log.error("IOExecptionunexpected.",ex);
- thrownewIllegalArgumentException("IOExecptionunexpected.");
- }
- }
- /**
- *Removeallthemulti-linecommentsfromablockoftext
- *@paramtextThetexttoremovemulti-linecommentsfrom
- *@returnThemulti-linecommentfreetext
- */
- publicstaticStringstripMultiLineComments(Stringtext)
- {
- if(text==null)
- {
- returnnull;
- }
- try
- {
- StringBufferoutput=newStringBuffer();
- //Commentrules:
- /*/Thisisstillacomment
- /*/**///Commentsdonotnest
- ///**/Thisisinacomment
- /*//*///Thesecond//isneededtomakethisacomment.
- //Firstwestripmultilinecomments.Ithinkthisisimportant:
- booleaninMultiLine=false;
- BufferedReaderin=newBufferedReader(newStringReader(text));
- while(true)
- {
- Stringline=in.readLine();
- if(line==null)
- {
- break;
- }
- if(!inMultiLine)
- {
- //Wearenotinamulti-linecomment,checkforastart
- intcstart=line.indexOf(COMMENT_ML_START);
- if(cstart>=0)
- {
- //ThiscouldbeaMLCononeline...
- intcend=line.indexOf(COMMENT_ML_END,cstart+COMMENT_ML_START.length());
- if(cend>=0)
- {
- //Acommentthatstartsandendsononeline
- //BUG:youcanhavemorethan1multi-linecommentonaline
- line=line.substring(0,cstart)+SPACE+line.substring(cend+COMMENT_ML_END.length());
- }
- else
- {
- //Arealmulti-linecomment
- inMultiLine=true;
- line=line.substring(0,cstart)+SPACE;
- }
- }
- else
- {
- //Wearenotinamultilinecommentandwehavn't
- //startedonesowearegoingtoignoreclosing
- //commentseveniftheyexist.
- }
- }
- else
- {
- //Weareinamulti-linecomment,checkfortheend
- intcend=line.indexOf(COMMENT_ML_END);
- if(cend>=0)
- {
- //Endofcomment
- line=line.substring(cend+COMMENT_ML_END.length());
- inMultiLine=false;
- }
- else
- {
- //Thecommentcontinues
- line=SPACE;
- }
- }
- output.append(line);
- output.append('/n');
- }
- returnoutput.toString();
- }
- catch(IOExceptionex)
- {
- log.error("IOExecptionunexpected.",ex);
- thrownewIllegalArgumentException("IOExecptionunexpected.");
- }
- }
- /**
- *Removeallblanklinesfromastring.
- *Ablanklineisdefinedtobealinewheretheonlycharactersarewhitespace.
- *Wealwaysensurethatthelinecontainsanewlineattheend.
- *@paramtextThestringtostripblanklinesfrom
- *@returnTheblanklinestrippedreply
- */
- publicstaticStringstripBlankLines(Stringtext)
- {
- if(text==null)
- {
- returnnull;
- }
- try
- {
- StringBufferoutput=newStringBuffer();
- BufferedReaderin=newBufferedReader(newStringReader(text));
- booleandoneOneLine=false;
- while(true)
- {
- Stringline=in.readLine();
- if(line==null)
- {
- break;
- }
- if(line.trim().length()>0)
- {
- output.append(line);
- output.append('/n');
- doneOneLine=true;
- }
- }
- if(!doneOneLine)
- {
- output.append('/n');
- }
- returnoutput.toString();
- }
- catch(IOExceptionex)
- {
- log.error("IOExecptionunexpected.",ex);
- thrownewIllegalArgumentException("IOExecptionunexpected.");
- }
- }
- /**
- *Removeallnewlinecharactersfromastring.
- *@paramtextThestringtostripnewlinecharactersfrom
- *@returnThestrippedreply
- */
- publicstaticStringstripNewlines(Stringtext)
- {
- if(text==null)
- {
- returnnull;
- }
- try
- {
- StringBufferoutput=newStringBuffer();
- BufferedReaderin=newBufferedReader(newStringReader(text));
- while(true)
- {
- Stringline=in.readLine();
- if(line==null)
- {
- break;
- }
- output.append(line);
- output.append(SPACE);
- }
- output.append('/n');
- returnoutput.toString();
- }
- catch(IOExceptionex)
- {
- log.error("IOExecptionunexpected.",ex);
- thrownewIllegalArgumentException("IOExecptionunexpected.");
- }
- }
- /**
- *Shrinkvariablenamestoaminimum.
- *@paramtextThejavascriptprogramtoshrinkthevariablenamesin.
- *@returnTheshrunkversionofthejavascriptprogram.
- */
- publicstaticStringshrinkVariableNames(Stringtext)
- {
- if(text==null)
- {
- returnnull;
- }
- thrownewUnsupportedOperationException("Variablenameshrinkingisnotsupported");
- }
- /**
- *<p>Escapesthecharactersina<code>String</code>usingJavaScriptStringrules.</p>
- *<p>EscapesanyvaluesitfindsintotheirJavaScriptStringform.
- *Dealscorrectlywithquotesandcontrol-chars(tab,backslash,cr,ff,etc.)</p>
- *
- *<p>Soatabbecomesthecharacters<code>'//'</code>and
- *<code>'t'</code>.</p>
- *
- *<p>TheonlydifferencebetweenJavastringsandJavaScriptstrings
- *isthatinJavaScript,asinglequotemustbeescaped.</p>
- *
- *<p>Example:
- *<pre>
- *inputstring:Hedidn'tsay,"Stop!"
- *outputstring:Hedidn/'tsay,/"Stop!/"
- *</pre>
- *</p>
- *
- *@paramstrStringtoescapevaluesin,maybenull
- *@returnStringwithescapedvalues,<code>null</code>ifnullstringinput
- */
- publicstaticStringescapeJavaScript(Stringstr)
- {
- if(str==null)
- {
- returnnull;
- }
- StringBufferwriter=newStringBuffer(str.length()*2);
- intsz=str.length();
- for(inti=0;i<sz;i++)
- {
- charch=str.charAt(i);
- //handleunicode
- if(ch>0xfff)
- {
- writer.append("//u");
- writer.append(hex(ch));
- }
- elseif(ch>0xff)
- {
- writer.append("//u0");
- writer.append(hex(ch));
- }
- elseif(ch>0x7f)
- {
- writer.append("//u00");
- writer.append(hex(ch));
- }
- elseif(ch<32)
- {
- switch(ch)
- {
- case'/b':
- writer.append('//');
- writer.append('b');
- break;
- case'/n':
- writer.append('//');
- writer.append('n');
- break;
- case'/t':
- writer.append('//');
- writer.append('t');
- break;
- case'/f':
- writer.append('//');
- writer.append('f');
- break;
- case'/r':
- writer.append('//');
- writer.append('r');
- break;
- default:
- if(ch>0xf)
- {
- writer.append("//u00");
- writer.append(hex(ch));
- }
- else
- {
- writer.append("//u000");
- writer.append(hex(ch));
- }
- break;
- }
- }
- else
- {
- switch(ch)
- {
- case'/'':
- //IfwewantedtoescapeforJavastringsthenwewould
- //notneedthisnextline.
- writer.append('//');
- writer.append('/'');
- break;
- case'"':
- writer.append('//');
- writer.append('"');
- break;
- case'//':
- writer.append('//');
- writer.append('//');
- break;
- case'<':
- writer.append("//u003c");
- break;
- case'>':
- writer.append("//u003e");
- break;
- default:
- writer.append(ch);
- break;
- }
- }
- }
- returnwriter.toString();
- }
- /**
- *<p>Returnsanuppercasehexadecimal<code>String</code>forthegiven
- *character.</p>
- *@paramchThecharactertoconvert.
- *@returnAnuppercasehexadecimal<code>String</code>
- */
- privatestaticStringhex(charch)
- {
- returnInteger.toHexString(ch).toUpperCase(Locale.ENGLISH);
- }
- /**
- *<p>UnescapesanyJavaScriptliteralsfoundinthe<code>String</code>.</p>
- *<p>Forexample,itwillturnasequenceof<code>'/'</code>and<code>'n'</code>
- *intoanewlinecharacter,unlessthe<code>'/'</code>isprecededbyanother
- *<code>'/'</code>.</p>
- *@paramstrthe<code>String</code>tounescape,maybenull
- *@returnAnewunescaped<code>String</code>,<code>null</code>ifnullstringinput
- */
- publicstaticStringunescapeJavaScript(Stringstr)
- {
- if(str==null)
- {
- returnnull;
- }
- StringBufferwriter=newStringBuffer(str.length());
- intsz=str.length();
- StringBufferunicode=newStringBuffer(4);
- booleanhadSlash=false;
- booleaninUnicode=false;
- for(inti=0;i<sz;i++)
- {
- charch=str.charAt(i);
- if(inUnicode)
- {
- //ifinunicode,thenwe'rereadingunicode
- //valuesinsomehow
- unicode.append(ch);
- if(unicode.length()==4)
- {
- //unicodenowcontainsthefourhexdigits
- //whichrepresentsourunicodechacater
- try
- {
- intvalue=Integer.parseInt(unicode.toString(),16);
- writer.append((char)value);
- unicode.setLength(0);
- inUnicode=false;
- hadSlash=false;
- }
- catch(NumberFormatExceptionnfe)
- {
- thrownewIllegalArgumentException("Unabletoparseunicodevalue:"+unicode+"cause:"+nfe);
- }
- }
- continue;
- }
- if(hadSlash)
- {
- //handleanescapedvalue
- hadSlash=false;
- switch(ch)
- {
- case'//':
- writer.append('//');
- break;
- case'/'':
- writer.append('/'');
- break;
- case'/"':
- writer.append('"');
- break;
- case'r':
- writer.append('/r');
- break;
- case'f':
- writer.append('/f');
- break;
- case't':
- writer.append('/t');
- break;
- case'n':
- writer.append('/n');
- break;
- case'b':
- writer.append('/b');
- break;
- case'u':
- //uh-oh,we'reinunicodecountry....
- inUnicode=true;
- break;
- default:
- writer.append(ch);
- break;
- }
- continue;
- }
- elseif(ch=='//')
- {
- hadSlash=true;
- continue;
- }
- writer.append(ch);
- }
- if(hadSlash)
- {
- //thenwe'reintheweirdcaseofa/attheendofthe
- //string,let'soutputitanyway.
- writer.append('//');
- }
- returnwriter.toString();
- }
- /**
- *Checktoseeifthegivenwordisreservedorabadideainanyknown
- *versionofJavaScript.
- *@paramnameThewordtocheck
- *@returnfalseifthewordisnotreserved
- */
- publicstaticbooleanisReservedWord(Stringname)
- {
- returnreserved.contains(name);
- }
- /**
- *Thearrayofjavascriptreservedwords
- */
- privatestaticfinalString[]RESERVED_ARRAY=newString[]
- {
- //ReservedandusedatECMAScript4
- "as",
- "break",
- "case",
- "catch",
- "class",
- "const",
- "continue",
- "default",
- "delete",
- "do",
- "else",
- "export",
- "extends",
- "false",
- "finally",
- "for",
- "function",
- "if",
- "import",
- "in",
- "instanceof",
- "is",
- "namespace",
- "new",
- "null",
- "package",
- "private",
- "public",
- "return",
- "super",
- "switch",
- "this",
- "throw",
- "true",
- "try",
- "typeof",
- "use",
- "var",
- "void",
- "while",
- "with",
- //ReservedforfutureuseatECMAScript4
- "abstract",
- "debugger",
- "enum",
- "goto",
- "implements",
- "interface",
- "native",
- "protected",
- "synchronized",
- "throws",
- "transient",
- "volatile",
- //ReservedinECMAScript3,unreservedat4besttoavoidanyway
- "boolean",
- "byte",
- "char",
- "double",
- "final",
- "float",
- "int",
- "long",
- "short",
- "static",
- //Ihaveseenthefolowinglistas'bestavoidedforfunctionnames'
- //butitseemswaytoallencompassing,soI'mnotgoingtoincludeit
- /*
- "alert","anchor","area","arguments","array","assign","blur",
- "boolean","button","callee","caller","captureevents","checkbox",
- "clearinterval","cleartimeout","close","closed","confirm",
- "constructor","date","defaultstatus","document","element","escape",
- "eval","fileupload","find","focus","form","frame","frames",
- "getclass","hidden","history","home","image","infinity",
- "innerheight","isfinite","innerwidth","isnan","java","javaarray",
- "javaclass","javaobject","javapackage","length","link","location",
- "locationbar","math","menubar","mimetype","moveby","moveto",
- "name","nan","navigate","navigator","netscape","number","object",
- "onblur","onerror","onfocus","onload","onunload","open","opener",
- "option","outerheight","outerwidth","packages","pagexoffset",
- "pageyoffset","parent","parsefloat","parseint","password",
- "personalbar","plugin","print","prompt","prototype","radio","ref",
- "regexp","releaseevents","reset","resizeby","resizeto",
- "routeevent","scroll","scrollbars","scrollby","scrollto","select",
- "self","setinterval","settimeout","status","statusbar","stop",
- "string","submit","sun","taint","text","textarea","toolbar",
- "top","tostring","unescape","untaint","unwatch","valueof","watch",
- "window",
- */
- };
- privatestaticSortedSetreserved=newTreeSet();
- /**
- *Foreasyaccess...
- */
- static
- {
- //TheJavascriptreservedwordsarraysowedon'tgenerateillegaljavascript
- reserved.addAll(Arrays.asList(RESERVED_ARRAY));
- }
- privatestaticfinalStringSPACE="";
- /**
- *Howdoesamultilinecommentstart?
- */
- privatestaticfinalStringCOMMENT_ML_START="/*";
- /**
- *Howdoesamultilinecommentend?
- */
- privatestaticfinalStringCOMMENT_ML_END="*/";
- /**
- *Howdoesasinglelinecommentstart?
- */
- privatestaticfinalStringCOMMENT_SL_START="//";
- /**
- *Sometimesweneedtoretainthecommentbecauseithasspecialmeaning
- */
- privatestaticfinalStringCOMMENT_RETAIN="#DWR";
- /**
- *Thelogstream
- */
- privatestaticfinalLoglog=LogFactory.getLog(JavascriptUtil.class);
- }
需要的JSON类我已经放到共享,你可以从
http://download.csdn.net/source/879579
下载
相关推荐
json格式与java类对象相互转换。json格式转换成java类对象,List,Map。类对象转换成json。
JSON对象转换成需要的工具类, JSON对象转换成需要的工具类,
对象与json相互转换,map转json,json转map等基础工具类
Json对象与json字符串互相转换处理工具
工具类---实现实体类与Json的转换
包含各种对象转换成json对象,还包含把对象中的属性转成hashmap 并且可以过滤为空的或者为null的对象
json与xml互相转换工具类
json 字符串转成c++类对象,json 字符串转成c++类对象
JSON转换为JAVA对象及日期格式转换处理 -
同样先将json字符串转换为json对象,再将json对象转换为java对象,如下所示。 JSONObject obj = new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象 将json对象转换为java对象 Person jb = (Person...
挺好用的一个JSON转换工具包,含Java端与JavaScript端的JSON对象转换工具类,使用时直接导入至项目源文件中并调用相关类及方法即可。此文件为JavaScript端使用,如需Java端的请移步我的另一上传资源“JSON对象转换...
该工具类包括多重的json字符串或Map或List的相互转换,该文件包括主要的jar包,可以快捷的使用工具
java 对象与json字符串互相转换工具类所需要的jar,java 对象与json字符串互相转换工具类
利用java反射将json字符串转成对象;
java的xml和json相互转换工具类,亲测直接用
非常好用的json转换工具类,之前在开发过程中总是遇到需要类似的工具类,但是没有好用的,现在找到一个好用的工具类,分享给大家
ajax json java 用法 json 将List、Object转换为Json格式字符串
安卓移动端中实现JSON和对象&数组的相互转换的工具类,代码里有注释
利用java反射机制实现Object转json.
1、将form中的数据利用本工具转换成json格式的字符串,再通过ajax传给服务器,从而可以实现无刷新的form提交。; 2、通过AJAX从服务器得到json格式的数据,然后使用本工具解析数据填入form。从而可以实现无刷新的...