Simple JSON開辟指南。本站提示廣大學習愛好者:(Simple JSON開辟指南)文章只能為提供參考,不一定能成為您想要的結果。以下是Simple JSON開辟指南正文
Simple JSON是Google開辟的Java JSON解析框架,基於Apache協定。
json-simple的主頁:http://www.jb51.net/softs/455885.html
下載的文件是:json_simple.jar
例子1:很便利的方法,應用JSONValue
System.out.println("=======decode======="); String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]"; Object obj=JSONValue.parse(s); JSONArray array=(JSONArray)obj; System.out.println("======the 2nd element of array======"); System.out.println(array.get(1)); System.out.println(); JSONObject obj2=(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
JSONParser parser=new JSONParser(); System.out.println("=======decode======="); String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]"; Object obj=parser.parse(s); JSONArray array=(JSONArray)obj; System.out.println("======the 2nd element of array======"); System.out.println(array.get(1)); System.out.println(); JSONObject obj2=(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:異常處置
String jsonText = "[[null, 123.45, \"a\\tb c\"]}, true"; JSONParser parser = new JSONParser(); try{ parser.parse(jsonText); } catch(ParseException pe){ System.out.println("position: " + pe.getPosition()); System.out.println(pe); }
履行成果:
position:25 Unexpected token RIGHT BRACE(}) at position 25.
例子4:容器工場
應用應用ContainerFactory類來創立一個容器工場。
String jsonText = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}"; JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory(){ public List creatArrayContainer() { return new LinkedList(); } public Map createObjectContainer() { return new LinkedHashMap(); } }; try{ Map json = (Map)parser.parse(jsonText, containerFactory); Iterator iter = json.entrySet().iterator(); System.out.println("==iterate result=="); while(iter.hasNext()){ Map.Entry entry = (Map.Entry)iter.next(); System.out.println(entry.getKey() + "=>" + entry.getValue()); } System.out.println("==toJSONString()=="); System.out.println(JSONValue.toJSONString(json)); } catch(ParseException pe){ System.out.println(pe); }
成果以下:
==iterate result== first=>123 second=>[4,5,6] third=>789 ==toJSONString()== {"first":123,"second":[4,5,6],"third":789}假如你不應用容器工場,Simple-JSON默許應用JSONObject和JSONArray。 例子5:可停的SAX式內容處置 SimpleJSON推舉一種簡略的可停的SAX方法的內容處置方法來處置文本流,用戶可以逗留在邏輯輸出流的隨意率性點,接著行止理其他邏輯,然後再持續先前的處置。不消期待全部流處置終了。以下是一個例子。 KeyFinder.java:
class KeyFinder implements ContentHandler{ private Object value; private boolean found = false; private boolean end = false; private String key; private String matchKey; public void setMatchKey(String matchKey){ this.matchKey = matchKey; } public Object getValue(){ return value; } public boolean isEnd(){ return end; } public void setFound(boolean found){ this.found = found; } public boolean isFound(){ return found; } public void startJSON() throws ParseException, IOException { found = false; end = false; } public void endJSON() throws ParseException, IOException { end = true; } public boolean primitive(Object value) throws ParseException, IOException { if(key != null){ if(key.equals(matchKey)){ found = true; this.value = value; key = null; return false; } } return true; } public boolean startArray() throws ParseException, IOException { return true; } public boolean startObject() throws ParseException, IOException { return true; } public boolean startObjectEntry(String key) throws ParseException, IOException { this.key = key; return true; } public boolean endArray() throws ParseException, IOException { return false; } public boolean endObject() throws ParseException, IOException { return true; } public boolean endObjectEntry() throws ParseException, IOException { return true; } }Main logic:
String jsonText ="{\"first\": 123, \"second\": [{\"k1\":{\"id\":\"id1\"}}, 4, 5, 6, {\"id\": 123}], \"third\": 789, \"id\": null}"; JSONParser parser =newJSONParser(); KeyFinder finder =newKeyFinder(); finder.setMatchKey("id"); try{ while(!finder.isEnd()){ parser.parse(jsonText, finder,true); if(finder.isFound()){ finder.setFound(false); System.out.println("found id:"); System.out.println(finder.getValue()); } } } catch(ParseException pe){ pe.printStackTrace(); }履行成果:
found id: id1 found id: 123 found id: null例子6:全部對象圖,用SAX式的解析
class Transformer implements ContentHandler{ private Stack valueStack; public Object getResult(){ if(valueStack == null || valueStack.size() == 0) return null; return valueStack.peek(); } public boolean endArray () throws ParseException, IOException { trackBack(); return true; } public void endJSON () throws ParseException, IOException {} public boolean endObject () throws ParseException, IOException { trackBack(); return true; } public boolean endObjectEntry () throws ParseException, IOException { Object value = valueStack.pop(); Object key = valueStack.pop(); Map parent = (Map)valueStack.peek(); parent.put(key, value); return true; } private void trackBack(){ if(valueStack.size() > 1){ Object value = valueStack.pop(); Object prev = valueStack.peek(); if(prev instanceof String){ valueStack.push(value); } } } private void consumeValue(Object value){ if(valueStack.size() == 0) valueStack.push(value); else{ Object prev = valueStack.peek(); if(prev instanceof List){ List array = (List)prev; array.add(value); } else{ valueStack.push(value); } } } public boolean primitive (Object value) throws ParseException, IOException { consumeValue(value); return true; } public boolean startArray () throws ParseException, IOException { List array = new JSONArray(); consumeValue(array); valueStack.push(array); return true; } public void startJSON () throws ParseException, IOException { valueStack = new Stack(); } public boolean startObject () throws ParseException, IOException { Map object = new JSONObject(); consumeValue(object); valueStack.push(object); return true; } public boolean startObjectEntry (String key) throws ParseException, IOException { valueStack.push(key); return true; } }Main方法邏輯:
String jsonString = <Input JSON text>; Object value = null; JSONParser parser = new JSONParser(); Transformer transformer = new Transformer(); parser.parse(jsonString, transformer); value = transformer.getResult();履行成果:
String jsonString =<Input JSON text>; Object value =null; JSONParser parser =newJSONParser(); value = parser.parse(jsonString);留意: JSONPauser不是線程平安的。
json_encode — 對變量停止 JSON 編碼。
解釋:string json_encode ($value ),前往 value 值的 JSON 情勢。
參數:待編碼的 value ,除resource 類型以外,可認為任何數據類型
該函數只能接收 UTF-8 編碼的數據(譯注:指字符/字符串類型的數據)
前往值:編碼勝利則前往一個以 JSON 情勢表現的 string 。