JSON (JavaScript Object Notation) is a lightweight data exchange format that uses a completely language-independent text format and is an ideal data exchange format. Meanwhile, JSON is a JavaScript native format, which means that no special API or toolkit is required to process JSON data in JavaScript.
Many json construction and parsing tools under JAVA are published on www.json.org. Among them, org.json and json-lib are relatively simple. The two are similar in use but there are still some differences. Next, we will introduce an example of the method of using org.json to construct and parse Json data.
For detailed explanation of the methods of constructing and parsing Json data using json-lib, please refer to my previous blog post: Two methods of constructing and parsing Json data using Java (Detailed explanation 1)
1. Introduction
The org.json package is another package used to convert beans, collections, maps, java arrays and XML and JSON. It is mainly used to parse Json data. It has detailed explanations on its official website http://www.json.org/. If you are interested, you can study it.
2. Download the jar dependency package
You can download it here
3. Introduction to basic methods
Since org.json cannot directly convert to beans, it needs to be converted through maps. For convenience, I have written a tool class JsonHelper here, which is used to convert Json with map and beans.
package com.json;import java.lang.reflect.Method;import java.text.ParseException;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import org.json.JSONException;import org.json.JSONObject;/*** * 1: Convert JavaBean to Map, JSONObject* 2: Convert Map to Javabean* 3: Convert JSONObject to Map, Javabean* * @author Alexia*/public class JsonHelper {/*** Convert Javabean to Map* * @param javaBean* javaBean* @return Map object*/public static Map toMap(Object javaBean) {Map result = new HashMap();Method[] methods = javaBean.getClass().getDeclaredMethods();for (Method method : methods) {try {if (method.getName().startsWith("get")) {String field = method.getName();field = field.substring(field.indexOf("get") + 3);field = field.toLowerCase().charAt(0) + field.substring(1);Object value = method.invoke(javaBean, (Object[]) null);result.put(field, null == value ? "" : value.toString());}} catch (Exception e) {e.printStackTrace();}}return result;}/*** Convert Json object to Map* * @param jsonObject* json object* @return Map object* @throws JSONException*/public static Map toMap(String jsonString) throws JSONException {JSONObject jsonObject = new JSONObject(jsonString);Map result = new HashMap();Iterator iterator = jsonObject.keys();String key = null;String value = null;while (iterator.hasNext()) {key = (String) iterator.next();value = jsonObject.getString(key);result.put(key, value);}return result;}/*** Convert JavaBean to JSONObject (transfer via Map)* * @param bean* javaBean* @return json object*/public static JSONObject toJSON(Object bean) {return new JSONObject(toMap(bean));}/*** Convert Map to Javabean* * @param javabean* javaBean* @param data* Map data*/public static Object toJavaBean(Object javabean, Map data) {Method[] methods = javabean.getClass().getDeclaredMethods();for (Method method : methods) {try {if (method.getName().startsWith("set")) {String field = method.getName();field = field.substring(field.indexOf("set") + 3);field = field.toLowerCase().charAt(0) + field.substring(1);method.invoke(javabean, new Object[] {data.get(field)});}} catch (Exception e) {}}return javabean;}/*** JSONObject to JavaBean* * @param bean* javaBean* @return json object* @throws ParseException* json parsing exception* @throws JSONException*/public static void toJavaBean(Object javabean, String jsonString)throws ParseException, JSONException {JSONObject jsonObject = new JSONObject(jsonString);Map map = toMap(jsonObject.toString());toJavaBean(javabean, map);}} 4. Demonstration example
Here are some basic common methods to test
package com.json;import java.text.ParseException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;/*** Use json-lib to construct and parse Json data* * @author Alexia* @date 2013/5/23* */public class OrgJsonTest {/*** Construct Json data* * @return* @throws JSONException*/public static String BuildJson() throws JSONException {// JSON format data parsing object JSONObject jo = new JSONObject();// Below construct two maps, a list and an Employee object Map<String, String> map1 = new HashMap<String, String>();map1.put("name", "Alexia");map1.put("sex", "female");map1.put("age", "23");Map<String, String> map2 = new HashMap<String, String>();map2.put("name", "Edward");map2.put("sex", "male");map2.put("age", "24");List<Map> list = new ArrayList<Map>();list.add(map1);list.add(map2);Employee employee = new Employee();employee.setName("wjl");employee.setSex("female");employee.setAge(24);// Convert Map to JSONArray dataJSONArray ja = new JSONArray();ja.put(map1);System.out.println("JSONArray object data format: ");System.out.println(ja.toString());// Convert Javabean to Json data (requires Map transit) JSONObject jo1 = JsonHelper.toJSON(employee);System.out.println("/nJson data format only contains Employee object: ");System.out.println(jo1.toString());// Construct Json data, including a map and a Json data containing Employee object jo.put("map", ja);jo.put("employee", jo1.toString());System.out.println("/n final constructed JSON data format: ");System.out.println(jo.toString());return jo.toString();}/*** parse Json data * * @param jsonString* Json data string* @throws JSONException* @throws ParseException*/public static void ParseJson(String jsonString) throws JSONException,ParseException {JSONObject jo = new JSONObject(jsonString);JSONArray ja = jo.getJSONArray("map");System.out.println("/n parses Json data into Map:");System.out.println("name: " + ja.getJSONObject(0).getString("name")+ " sex: " + ja.getJSONObject(0).getString("sex") + " age: "+ ja.getJSONObject(0).getInt("age"));String jsonStr = jo.getString("employee");Employee emp = new Employee();JsonHelper.toJavaBean(emp, jsonStr);System.out.println("/n parse Json data into Employee object:");System.out.println("name: " + emp.getName() + " sex: " + emp.getSex()+ " age: " + emp.getAge());}/*** @param args* @throws JSONException* @throws ParseException*/public static void main(String[] args) throws JSONException, ParseException {// TODO Auto-generated method stubParseJson(BuildJson());}} The operation results are as follows
5. Comparison with json-lib
The use of json-lib and org.json is almost the same. I have summarized two differences:
1. org.json is much lighter than json-lib. The former does not rely on any other jar packages, while the latter depends on lang, logging, beanutils, collections and other components of ezmorph and commons.
2. json-lib is much more convenient than org.json when constructing beans and parsing beans. json-lib can directly convert with beans, while org.json cannot directly convert with beans and requires maps as transit. If you convert beans to json data, you must first convert the beans to maps and then convert the maps to json, which is more troublesome.
In short, the same sentence is still the best thing for you. Everyone should choose which method to use to analyze it as needed. Finally, I will introduce two tools to analyze Json data: one is the online tool JSON Edit (http://braincast.nl/samples/jsoneditor/); the other is Eclipse plugin JSON Tree Analyzer, both of which are very useful and are recommended for everyone to use!
The above is the relevant knowledge of the two methods (detailed explanation) used by the editor to introduce to you about Java to construct and parsing Json data. I hope it will be helpful to you!