Conversion between string and json in java
1. There are three methods to convert string to json: string directly to jsonString json = "{\" 2 \ ": \" efg \ ", \" 1 \": \ "abc \"} "; JSONObject json_test = JSONObject. fromObject (json); double quotation marks of string can be escaped. This applies to the second type with shorter strings: Convert string to list and convert it to jsonList <String> list = new ArrayList <String> (); list. add ("username"); list. add ("age"); list. add ("sex"); JSONArray array = new JSONArray (); array. add (list); you can use the add function of list to splice the required strings. However, this function can only use jsonarry. Method 3: Convert string to map and convert it to json Map <String, string> map = new HashMap <String, String> (); map. put ("1", "abc"); map. put ("2", "efg"); JSONArray array_test = new JSONArray (); array_test.add (map); JSONObject jsonObject = JSONObject. fromObject (map); here you can use map to convert a string to JSONArray or JSONObject, but the keys here cannot use int Type 1. Convert json to string to construct json first: JSONObject string_to_json = JSONObject. fromObject ("{\" data \ ": {\" pages \ ": [{\" comment \ ": \" just for test \"}, {\ "comment \": \ "just for test \"}], \ "total_count \": 2 },\ "errcode \": 0 }"); for JSONObject, you can directly use JSONObject json_to_data = aggregate ("data"); For JSONArray, you can use the first two types: JSONArray json_to_strings = json_to_data.getJSONArray ("pages "); // retrieve the JSONArray contained in JSONObject for (Object object: json_to_strings) {// cyclically read JSONObject json_to_string = JSONObject. fromObject (object); json_to_string.get ("pages");} type 2: JSONArray json_to_strings_test = json_to_data1.getJSONArray ("pages "); // retrieve the JSONArray contained in JSONObject for (int I = 0; I <json_to_strings_test.size (); I ++) {// cyclically read JSONObject json_to_string1 = json_to_strings_test.getJSONObject (I );}