Simple JSON is a Java JSON parsing framework developed by Google, based on the Apache protocol.
json-simple's homepage://www.VeVB.COM/softs/455885.html
The downloaded file is: json_simple.jar
Example 1: Very convenient way to use JSONValue
System.out.println("=========================================; 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);JSONObject inherits Map, while JSONArray inherits List, so you can use the standard way of Map and List to use JSONObject and JSONArray.
JSONValue can use arrays or objects.
Example 2: Quick way, using JSONParser
JSONParser parser=new JSONParser(); System.out.println("==================================================================================== 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);Using JSONParser requires the exception to be caught.
Example 3: Exception handling
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); }Execution results:
position:25 Unexpected token RIGHT BRACE(}) at position 25.
Example 4: Container Factory
Use the ContainerFactory class to create a container factory.
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); }The results are as follows:
==iterate result== first=>123 second=>[4,5,6] third=>789 ==toJSONString()== {"first":123,"second":[4,5,6],"third":789} If you don't use container factories, Simple-JSON uses JSONObject and JSONArray by default. Example 5: Stopable SAX content processing SimpleJSON recommends a simple stopable SAX content processing method to process text streams. The user can stay at any point in the logical input stream, then process other logic, and then continue with the previous processing. Don't wait for the entire stream to be processed. Here is an example. 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(); } Execution results:found id: id1 found id: 123 found id: nullExample 6: The entire object graph is analyzed using SAX-like
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 consumptionValue(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 { consumptionValue(value); return true; } public boolean startArray () throws ParseException, IOException { List array = new JSONArray(); consumptionValue(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 method logic:String jsonString = <Input JSON text>; Object value = null; JSONParser parser = new JSONParser(); Transformer transformer = new Transformer(); parser.parse(jsonString, transformer); value = transformer.getResult();Execution results:
String jsonString =<Input JSON text>; Object value =null; JSONParser parser =newJSONParser(); value = parser.parse(jsonString);Note: JSONPauser is not thread-safe.
json_encode - JSON encoding of variables.
Description: string json_encode ($value ), returns the JSON form of the value value.
Parameters: The value to be encoded can be any data type except for the resource type
This function can only accept UTF-8 encoded data (translation note: refers to data of character/string type)
Return value: If the encoding is successful, a string represented in JSON will be returned.