Here is a brief introduction to how to use the Json-lib Toolkit to complete the transformation between a Java object (or collection) and a JSON object (or collection) ~
1. Translating Java objects into JSON (creating JSON)
Key class: Jsonobject Jsonobject = jsonobject.from (Object obj);
Instructions for use: Just pass the Java object into the method, then you can get a jsonobject, then you can directly json.tostring (); Output json~
Example:
@Test publicvoidthrows Exception { new Employee ("Zhangsan", "n"); = Jsonobject.fromobject (employee); System.out.println (Jsonobject.tostring ()); }
Output Result:
As you can see from the above output, the order of the properties of the JSON object Jsonobject output is unordered ~
2. String converted to Java object (parsing JSON)
Key class: Jsonobject JSON = new Jsonobject (String jsonstring);
Json.get (String key); Gets the value according to key. A key is a property name for a Java object, and value is the property value
Instructions for use: First, the JSON string is passed into the constructor of the Jsonobject object, a Jsonobject object is obtained, and the corresponding data is obtained through the object to construct a Java object.
Example:
@Test publicvoid Testparsejson () { = "{\" age\ ": \" 12\ ", \" name\ ": \ "Zhangsan\"} "; New jsonobject (). Fromobject (jsonstring); System.out.println (Json.get ("name")); System.out.println (Json.get ("age"));
Output Result:
ZhangSan12
Appendix: Specific implementation of employee code
Public classEmployee {PrivateString name; PrivateString age; PublicString GetName () {returnname; } PublicString getage () {returnAge ; } Public voidsetName (String name) { This. Name =name; } Public voidsetage (String age) { This. Age =Age ; } PublicEmployee (string name, String age) {Super(); This. Name =name; This. Age =Age ; } PublicEmployee () {Super(); } @Override PublicString toString () {return"[Name=" +name+ ", age=" +age+ "]"; }}
Extended reading:
Conversion between the Java collection JSON collection
Conversion between Java object JSON (JSON-LIB)