1. The difference between JSON array and object
JSONArray is to convert the data into array form:
strArray:[{“address”:”北京市西城区”,”age”:”23”,”name”:”JSON”}]
When using it, you need to read the data in json in array mode, strArray[0].address;
JSONObject is to convert the data into a object form:
strJson:{“address”:”北京市西城区”,”age”:”23”,”name”:”JSON”}
When using, directly use the object method to read the data in json, strArray.address;
2. Convert the object to JSON
First convert the java object Convert to json object, after converting json object to json string
//1、使用JSONObject JSONObject json = JSONObject.fromObject(stu); //2、使用JSONArray JSONArray array=JSONArray.fromObject(stu); String strJson=json.toString(); String strArray=array.toString();
3. Convert json string to java object
Also first convert json string to json object, and then convert the json object into a java object, as shown below.
JSONObject obj = new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象
Convert json object to java object
Person jb = (Person)JSONObject.toBean(obj,Person.class);//将建json对象转换为Person对象
The above is the detailed content of How to convert java objects and json back and forth. For more information, please follow other related articles on the PHP Chinese website!