Simple JSON开发指南
SimpleJSON是Google开发的JavaJSON解析框架,基于Apache协议。
json-simple的主页:
下载的文件是:json_simple.jar
例子1:很方便的方式,使用JSONValue
System.out.println("=======decode======="); Strings="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]"; Objectobj=JSONValue.parse(s); JSONArrayarray=(JSONArray)obj; System.out.println("======the2ndelementofarray======"); System.out.println(array.get(1)); System.out.println(); JSONObjectobj2=(JSONObject)array.get(1); System.out.println("======field\"1\"=========="); System.out.println(obj2.get("1")); s="{}"; obj=JSONValue.parse(s); System.out.println(obj); s="[5,]"; obj=JSONValue.parse(s); System.out.println(obj); s="[5,,2]"; obj=JSONValue.parse(s); System.out.println(obj);
JSONObject是继承Map的,而JSONArray是继承List的,所以你可以用Map和List的标准方式来使用JSONObject和JSONArray。
而JSONValue则可以使用数组也可以用对象。
例子2:快速的方式,使用JSONParser
JSONParserparser=newJSONParser(); System.out.println("=======decode======="); Strings="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]"; Objectobj=parser.parse(s); JSONArrayarray=(JSONArray)obj; System.out.println("======the2ndelementofarray======"); System.out.println(array.get(1)); System.out.println(); JSONObjectobj2=(JSONObject)array.get(1); System.out.println("======field\"1\"=========="); System.out.println(obj2.get("1")); s="{}"; obj=parser.parse(s); System.out.println(obj); s="[5,]"; obj=parser.parse(s); System.out.println(obj); s="[5,,2]"; obj=parser.parse(s); System.out.println(obj);
使用JSONParser需要捕获异常。
例子3:异常处理
StringjsonText="[[null,123.45,\"a\\tbc\"]},true"; JSONParserparser=newJSONParser(); try{ parser.parse(jsonText); } catch(ParseExceptionpe){ System.out.println("position:"+pe.getPosition()); System.out.println(pe); }
执行结果:
position:25UnexpectedtokenRIGHTBRACE(})atposition25.
例子4:容器工厂
使用使用
StringjsonText="{\"first\":123,\"second\":[4,5,6],\"third\":789}"; JSONParserparser=newJSONParser(); ContainerFactorycontainerFactory=newContainerFactory(){ publicListcreatArrayContainer(){ returnnewLinkedList(); } publicMapcreateObjectContainer(){ returnnewLinkedHashMap(); } }; try{ Mapjson=(Map)parser.parse(jsonText,containerFactory); Iteratoriter=json.entrySet().iterator(); System.out.println("==iterateresult=="); while(iter.hasNext()){ Map.Entryentry=(Map.Entry)iter.next(); System.out.println(entry.getKey()+"=>"+entry.getValue()); } System.out.println("==toJSONString()=="); System.out.println(JSONValue.toJSONString(json)); } catch(ParseExceptionpe){ System.out.println(pe); }
结果如下:
==iterateresult==first=>123second=>[4,5,6]third=>789==toJSONString()== {"first":123,"second":[4,5,6],"third":789}如果你不使用容器工厂,Simple-JSON默认使用JSONObject和JSONArray。 例子5:可停的SAX式内容处理 SimpleJSON推荐一种简单的可停的SAX方式的内容处理方式来处理文本流,用户可以停留在逻辑输入流的任意点,接着去处理其他逻辑,然后再继续先前的处理。不用等待整个流处理完毕。以下是一个例子。 KeyFinder.java:
classKeyFinderimplementsContentHandler{ privateObjectvalue; privatebooleanfound=false; privatebooleanend=false; privateStringkey; privateStringmatchKey; publicvoidsetMatchKey(StringmatchKey){ this.matchKey=matchKey; } publicObjectgetValue(){ returnvalue; } publicbooleanisEnd(){ returnend; } publicvoidsetFound(booleanfound){ this.found=found; } publicbooleanisFound(){ returnfound; } publicvoidstartJSON()throwsParseException,IOException{ found=false; end=false; } publicvoidendJSON()throwsParseException,IOException{ end=true; } publicbooleanprimitive(Objectvalue)throwsParseException,IOException{ if(key!=null){ if(key.equals(matchKey)){ found=true; this.value=value; key=null; returnfalse; } } returntrue; } publicbooleanstartArray()throwsParseException,IOException{ returntrue; } publicbooleanstartObject()throwsParseException,IOException{ returntrue; } publicbooleanstartObjectEntry(Stringkey)throwsParseException,IOException{ this.key=key; returntrue; } publicbooleanendArray()throwsParseException,IOException{ returnfalse; } publicbooleanendObject()throwsParseException,IOException{ returntrue; } publicbooleanendObjectEntry()throwsParseException,IOException{ returntrue; } }Mainlogic:
StringjsonText="{\"first\":123,\"second\":[{\"k1\":{\"id\":\"id1\"}},4,5,6,{\"id\":123}],\"third\":789,\"id\":null}"; JSONParserparser=newJSONParser(); KeyFinderfinder=newKeyFinder(); finder.setMatchKey("id"); try{ while(!finder.isEnd()){ parser.parse(jsonText,finder,true); if(finder.isFound()){ finder.setFound(false); System.out.println("foundid:"); System.out.println(finder.getValue()); } } } catch(ParseExceptionpe){ pe.printStackTrace(); }执行结果:
foundid: id1 foundid: 123 foundid: null例子6:整个对象图,用SAX式的解析
classTransformerimplementsContentHandler{ privateStackvalueStack; publicObjectgetResult(){ if(valueStack==null||valueStack.size()==0) returnnull; returnvalueStack.peek(); } publicbooleanendArray()throwsParseException,IOException{ trackBack(); returntrue; } publicvoidendJSON()throwsParseException,IOException{} publicbooleanendObject()throwsParseException,IOException{ trackBack(); returntrue; } publicbooleanendObjectEntry()throwsParseException,IOException{ Objectvalue=valueStack.pop(); Objectkey=valueStack.pop(); Mapparent=(Map)valueStack.peek(); parent.put(key,value); returntrue; } privatevoidtrackBack(){ if(valueStack.size()>1){ Objectvalue=valueStack.pop(); Objectprev=valueStack.peek(); if(previnstanceofString){ valueStack.push(value); } } } privatevoidconsumeValue(Objectvalue){ if(valueStack.size()==0) valueStack.push(value); else{ Objectprev=valueStack.peek(); if(previnstanceofList){ Listarray=(List)prev; array.add(value); } else{ valueStack.push(value); } } } publicbooleanprimitive(Objectvalue)throwsParseException,IOException{ consumeValue(value); returntrue; } publicbooleanstartArray()throwsParseException,IOException{ Listarray=newJSONArray(); consumeValue(array); valueStack.push(array); returntrue; } publicvoidstartJSON()throwsParseException,IOException{ valueStack=newStack(); } publicbooleanstartObject()throwsParseException,IOException{ Mapobject=newJSONObject(); consumeValue(object); valueStack.push(object); returntrue; } publicbooleanstartObjectEntry(Stringkey)throwsParseException,IOException{ valueStack.push(key); returntrue; } }Main方式逻辑:
StringjsonString=<InputJSONtext>; Objectvalue=null; JSONParserparser=newJSONParser(); Transformertransformer=newTransformer(); parser.parse(jsonString,transformer); value=transformer.getResult();执行结果:
StringjsonString=<InputJSONtext>; Objectvalue=null; JSONParserparser=newJSONParser(); value=parser.parse(jsonString);注意: JSONPauser不是线程安全的。
json_encode—对变量进行JSON编码。
说明:stringjson_encode($value),返回value值的JSON形式。
参数:待编码的value,除了resource类型之外,可以为任何数据类型
该函数只能接受UTF-8编码的数据(译注:指字符/字符串类型的数据)
返回值:编码成功则返回一个以JSON形式表示的string。