Use of Json and Jsonlib
JSON (Jvascript Object Notation) (official website: http://www.json.org/) is a lightweight data interchange format. Easy for people to read and write. It is also easy for machine parsing and generation. It is based on JavaScript programming Language, Standard ECMA-262 a subset of 3rd Edition-december 1999. JSON takes a completely language-independent text format, but also uses a similar idiom to the C language family (c, C + +, C #, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language.
- Two kinds of structure of JSON
1. Collection of name/value pairs (A collection of name/value pairs). In different languages, it is understood as objects (object), record (record), structure (struct), Dictionary (dictionary), hash table (hash table), keyed list (keyed list), or associative array (associative Array). In the Java language, we can interpret it as HashMap.
An object is an unordered collection of "name/value pairs". An object starts with "{" (opening parenthesis) and "}" (the closing parenthesis) ends. Each "name" is followed by a ":" (colon); "' Name/value ' pair ' is separated by", "(comma).
Example: var json = {"name": "Jack", "age": All, "Marray": true};
2. Ordered list of values (an ordered list of values). In most languages, it is understood as an array (array or List).
An array is an ordered collection of values (value). An array begins with "[" (the left square bracket), and "]" (the right square bracket) ends. Use "," (comma) to separate values.
Example: var json = ["Jack", "Rose", "Tom", 89,true,false];
Json-lib is a Java class library (official website: http://json-lib.sourceforge.net/) to achieve the following functions:
- Convert JavaBeans, maps, collections, Java arrays, and XML into JSON format data
- Convert JSON format data to a JavaBeans object
Json-lib Required JAR Package
- Commons-beanutils-1.8.3.jar
- Commons-collections-3.2.1.jar
- Commons-lang-2.6.jar
- Commons-logging-1.1.1.jar
- Ezmorph-1.0.6.jar
- Json-lib-2.4-jdk15.jaR
1. Parse the Array into a Json string. Use Jsonarray to parse the Array type:
PackageCn.sunzn.json;ImportJava.util.ArrayList;ImportJava.util.HashSet;ImportJava.util.List;ImportJava.util.Set;ImportNet.sf.json.JSONArray;PublicClassJsonlib {PublicStaticvoidMain (string[] args) {/*** Parses an Array into a Json string*/string[] str = {"Jack", "Tom", "All", "true"}; Jsonarray JSON =Jsonarray.fromobject (str); SYSTEM.ERR.PRINTLN (JSON);/*** For image arrays, note numbers and cloth values*/object[] o = {"Beijing", "Shanghai", 89,True, 90.87}; JSON =Jsonarray.fromobject (o); SYSTEM.ERR.PRINTLN (JSON);/*** Using the Collection class*/ list<string> List = new arraylist<string> (); List.add ("Jack" Jsonarray.fromobject (list); SYSTEM.ERR.PRINTLN (JSON); /** * use Set set */ set<object> Set = new hashset<object> (); Set.add ("Hello" true Jsonarray.fromobject (set); SYSTEM.ERR.PRINTLN (JSON); }}
The results of the operation are as follows:
["Jack", "Tom", "All", "true"] ["Beijing", "Shanghai", "true,90.87"] ["Jack", "Rose"][99,true, "Hello"]
2. Parse the Javabean/map into a JSON string. Using Jsonobject parsing:
PackageCn.sunzn.json;ImportJava.util.HashMap;ImportJava.util.Map;ImportNet.sf.json.JSONObject;PublicClassJsonlib {@SuppressWarnings ("static-access")PublicStaticvoidMain (string[] args) {/*** Analytic HashMap*/map<string, object> map =New Hashmap<string, object>(); Map.put ("name", "Tom"); Map.put ("Age"); Jsonobject jsonobject = jsonobject.fromobject (map); System.out.println (Jsonobject); /** * Parse JavaBean */person person = new Person ("A001", "Jack"); jsonobject = Jsonobject.fromo Bject (person); System.out.println (Jsonobject); /** * Parse nested objects * /map.put ("person", person); jsonobject = jsonobject.fromobject (map); System.out.println (Jsonobject); }}
The results of the operation are as follows:
{"Age": "Name": "Tom"} {"id": "A001", "Name": "Jack"} {"Person": {"id": "A001", "Name": "Jack"}, "Age": "Name" ":" Tom "}
3. Using the Jsonconfig-over property: for Javabean/map
PackageCn.sunzn.json;ImportNet.sf.json.JSONObject;Import Net.sf.json.JsonConfig; public class Jsonlib { Span style= "COLOR: #0000ff" >public static void main (string[] args) {jsonconfig config = new Jsonconfig (); Config.setexcludes (new string[] {"Name"}); // Specifies which properties are not included in the conversion. new person ("A001", "Jack" // passed in the previous configuration object when converting System.out.println (Jsonobject); }}
The result of the operation is as follows, and we can see that the name attribute is filtered out in the running result:
{"id": "A001"}
4. Convert the Json string to an Array:
Package Cn.sunzn.json; Import java.util.Arrays; Import Net.sf.json.JSONArray; Classvoid main (string[] args) {Jsonarray Jsonarray = Jsonarray.fromobject ("[89,90,99]"); Object array = Jsonarray.toarray (jsonarray); SYSTEM.OUT.PRINTLN (array); System.out.println (Arrays.aslist ((object[]) array); }}
The results of the operation are as follows:
[Ljava.lang.object;@1e5003f6[89, 90, 99]
5. Turn the Json string into Javabean/map:
PackageCn.sunzn.json;ImportJava.util.Map;ImportNet.sf.json.JSONObject;PublicClassJsonlib {@SuppressWarnings ("unchecked")PublicStaticvoidMain (string[] args) {/*** Convert a Json-form string to a Map*/ String str = "{\" name\ ": \" tom\ ", \" age\ ":" ; Jsonobject jsonobject = Jsonobject.fromobject (str); map<string, object> map = (map<string, object>) Jsonobject.tobean (jsonobject, Map.class); SYSTEM.OUT.PRINTLN (map); /** * Converts a Json-form string to JavaBean */ str = "{\" id\ ": \" a001\ ", \" name\ ": \" Jack\ "}" ; Jsonobject = Jsonobject.fromobject (str); System.out.println (Jsonobject); Person person = (person) jsonobject.tobean (jsonobject, Person. Class
The results of the operation are as follows:
{age=90, name=Tom}person [id=a001, Name=jack]
When converting a Json-like string to JavaBean, it is important to note that there must be no parameter constructor in the JavaBean, or the following error cannot be found for the initialization method:
Exception in thread "main" Net.sf.json.jsonexception:java.lang.nosuchmethodexception:cn.sunzn.json.person.<init >() at Net.sf.json.JSONObject.toBean (jsonobject.java:288) at Net.sf.json.JSONObject.toBean ( jsonobject.java:233) at Cn.sunzn.json.JsonLib.main (jsonlib.java:23) caused by: Java.lang.nosuchmethodexception:cn.sunzn.json.person.<init>() at Java.lang.Class.getConstructor0 ( Unknown source) at Java.lang.Class.getDeclaredConstructor (Unknown source) at Net.sf.json.util.newbeaninstancestrategy$defaultnewbeaninstancestrategy.newinstance ( Newbeaninstancestrategy.java:55) at Net.sf.json.JSONObject.toBean (jsonobject.java:282) ... 2 More
Parsing of JSON-formatted data in Java background