JSON is the most popular lightweight data exchange language at present (nothing). Although it is a subset of javascript. But because it is a text format independent of languages, it can be supported by almost all programming languages.
The following is a summary of parsing json data in the Java language.
To parse json, you must first import the tool class that parses json.
import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;
We all know that there are json objects and json arrays in JSON (json data is an array of json objects)
json object in braces
For example: {"key","value"}
json array in brackets
For example: [{"key","value"},{"key","value"}]
1 parsing json object
Assume that the data is {"key","value"}
String jsonData = "{/"key/",/"value/"}"//Escape special characters with backslash, which has nothing to do with json String value = null;try{JSONObject josonObject = new JSONObject(jsonData);value = jsonObject.getString("key");//Here the data in json is parsed out}catch (Exception e){e.printStackTrace();}Sometimes the data of a json object is a json array. The following method can be used to extract the JSON object from the JSON object.
JSONArray jsonArray = jsonObject.getJSONArray("arrayKey");2. Parsing JSON arrays
String jsonData = "[{/"key/",/"value/"},{/"key/",/"value/"}]";JSONArray jsonArray = new JSONArray(jsonData); for(int i=0;i<jsonArray .length();i++){ //Tranquility through all JSON array elements JSONObject jsonObject = jsonArray .getJSONObject(i); String value= foodJsonObject.getString("value");}The above is a summary of the methods of parsing JSON data. Because of the flexibility of JSON data, you need to use these methods flexibly to parse the data well. ,
Summarize
The above is all the content of this article about Java parsing JSON data. I hope it will be helpful to everyone. Interested friends can continue to refer to other Java-related topics on this website. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!