Data storage (iii) -- JSON Data Processing
JSON is a lightweight data exchange format with good readability and ease of writing. It can exchange data between different platforms. JSON adopts a highly compatible text format and has behaviors similar to the C language system. JSON can convert a Java object to a json string and convert a json string to Java. It is more lightweight than XML, and Json is relatively lightweight and simple to use. JSON data format is widely used in Android for communication between clients and servers. It is very convenient for network data transmission and resolution.
JSONObject-this is the basic unit in the system for JSON definition. It contains a pair of Key/Value values.
JSONArray -- it represents a group of ordered values. The format of toString output is enclosed in square brackets. Values are separated by commas (,) ([value1, value2, value3]).
JSONStringer -- this class can help you quickly and conveniently create JSONtext. Its biggest advantage is that it can reduce program exceptions caused by format errors. referencing this class can automatically create JSON text in strict accordance with the JSON syntax rules (syntaxrules. Each JSONStringer object can only create one JSON text.
JSONTokener -- json parsing class
JSONException -- exceptions in json
The following describes how to convert the Book object in data storage (2) to a String object in Json format.
Public static String ObjectToJsonString (List
Books) throws JSONException {JSONStringer stringer = new JSONStringer (); stringer. object (); stringer. key ("books"); stringer. array (); for (int I = 0; I
Convert String to Book object
Public static List
JsonStringToObject (String str) throws JSONException {List
Books = new ArrayList
(); JSONTokener jsonTokener = new JSONTokener (str); JSONObject jsonObject = (JSONObject) jsonTokener. nextValue (); JSONArray array = jsonObject. getJSONArray ("books"); for (int I = 0; I note:
GetXXX () can convert the value of the key to be obtained to the specified type. If the key cannot be converted or there is no value, JSONException is thrown.
OptXXX () is also the value of the key to be obtained to the specified type. If the key cannot be converted or there is no value, the value provided by the user or the default value is returned.