Json.parseobject, is to convert the JSON string to the corresponding object; json.tojsonstring is to convert the object to a JSON string. In the pre-background transfer process, the JSON string is quite common, there is not much to describe its function, directly to give a small example of the application, to help understand the use of these two methods.
First use Maven to introduce Fastjson:
<?XML version= "1.0" encoding= "UTF-8"?><Projectxmlns= "http://maven.apache.org/POM/4.0.0"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion> <groupId>Com.wujiang.test</groupId> <Artifactid>Test</Artifactid> <version>1.0-snapshot</version> <Properties> <fastjson_version>1.2.28</fastjson_version> </Properties> <Dependencies> <Dependency> <groupId>Com.alibaba</groupId> <Artifactid>Fastjson</Artifactid> <version>${fastjson_version}</version> </Dependency> </Dependencies></Project>
Define a model class, employee, with four attributes, as follows:
Packagejsontest;Importjava.util.Date;/** * @authorWujiang *@version1.0.0. * @date 2017/4/30*/ Public classStaff {PrivateString name; PrivateInteger age; PrivateString sex; PrivateDate birthday; //omit getter and setter methods@Override PublicString toString () {return"staff{" + "name=" + name + "\" + ", age=" + Age + ", sex= '" + sex + "\" + ", birthday=" + Birthday + '} '; }}
OK, next, test the Json.parseobject and Json.tojsonstring methods. There is a deliberate telephone in the JSON string, and one less birthday in the staff to see what happens to the output object:
Packagejsontest;ImportCom.alibaba.fastjson.JSON;/** * @authorWujiang *@version1.0.0. * @date 2017/4/30*/ Public classJsontest { Public Static voidMain (string[] args) {/*** JSON string converted to object*/String jsonstring= "{name: ' Antony ', Age: '", Sex: ' Male ', Telephone: ' 88888 '} "; Staff= Json.parseobject (jsonstring, staff.class); System.out.println (Staff.tostring ()); /*** Object converted to JSON string*/String jsonstr=json.tojsonstring (staff); System.out.println (JSONSTR); }}
Output Result:
Staff{name= ' Antony ', age=12, sex= ' Male ', birthday=null} {"age": "Name": "Antony", "Sex": "Male" }// If age is a string type, then the output turns to //{"Age": "Antony", "name": "The", "Sex": "Male"}
When you json.parseobject, you will populate the property with the same name. For JSON strings, there are no properties for the model class, NULL for the model class, and no processing for JSON string properties.
Json.parseobject and Json.tojsonstring