1, first of all to understand a few concepts
JSON object, JSON array, JSON string
JSON objects can be represented by jsonobject
The JSON array can be represented by Jsonarray
A JSON string is just a string of type
And then look at the following code that's a lot easier.
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import Net.sf.json.JSONArray;
Import Net.sf.json.JSONObject;
public class Test {
public static void Main (string[] args) {
The list collection transforms the JSON array (consistent with the array)
list<string> list = new arraylist<string> ();
List.add ("a");
List.add ("B");
Jsonarray Jsonarray = jsonarray.fromobject (list);
System.err.println (Jsonarray.tostring ());
Map Collections Convert JSON objects
map<string, string> map = new hashmap<string, string> ();
Map.put ("1", "1");
Map.put ("2", "2");
Jsonobject jsonobject = jsonobject.fromobject (map);
System.out.println (Jsonobject.tostring ());
Converts the map collection to a JSON array (JavaBean is consistent with the map type)
Jsonarray jsonArray2 = jsonarray.fromobject (map);
System.out.println (Jsonarray2.tostring ());
General data (JSON string) converted to JSON
Jsonarray jsonArray3 = Jsonarray.fromobject ("[' 1 ', ' 2 ', ' 4 ']");
System.out.println (JSONARRAY3);
}
}
More complex conversions are based on the underlying conversions.
An array object that has recently been used in a project to convert a JSON string to a custom bean
First, convert the string to a JSON array, and then use the Jsonarray.tostring method to
Converts the specified JSON array to the corresponding custom Bean object
String users = Request.getparameter ("users");
Jsonarray Jsonarray = jsonarray.fromobject (users);
User[]users2 = (user[]) Jsonarray.toarray (Jsonarray, User.class);
Parsing JSON data using Json-lib