Java code
public class User { private String username; private String password; Public String GetUserName () { return username; } public void Setusername (String username) { this.username = username; } Public String GetPassword () { return password; } public void SetPassword (String password) { this.password = password; } }
Normal JavaBean (take user as example) to JSON format
1. Turn into Jsonarray type
User user = new user ();
User.setusername ("CXL");
User.setpassword ("1234");
Jsonarray JSON = jsonarray.fromobject (user);
SYSTEM.OUT.PRINTLN (JSON);//[{"password": "1234", "username": "CXL"}]
Response.getwriter (). Print (json.tostring ());
Fetch data in JS file
$.getjson ("Http://localhost:8080/jQueryDemo/servlet/UserServlet", null,function (data) {
alert (data[0].username);
alert (Data[0].password);
});
2. Turn into Jsonobject type
Jsonobject jsonobj = jsonobject.fromobject (user);
System.out.println (jsonobj);//{"password": "1234", "username": "CXL"}
Response.getwriter (). print (jsonobj);
Fetch data in JS file
alert (data.username);
alert (Data.password);
List turns into JSON format
list<user> users = new arraylist<user> ();
User user = new user ();
User.setusername ("CXL");
User.setpassword ("1234");
User U = new user ();
U.setusername ("Lhl");
U.setpassword ("1234");
Users.add (user);
Users.add (U);
1. Turn into Jsonarray type
Jsonarray JSON = jsonarray.fromobject (users);
System.out.println (Json.tostring ());
[{"Password": "1234", "username": "CXL"},{"password": "1234", "username": "Lhl"}]
Response.getwriter (). Print (json.tostring ());
JS Data: Alert (Alert (data[0].username));
2. Turn into Jsonobject type
Do not use jsonobject Jsonobj = Jsonobject.fromobject (users) directly;
This can be done in the following ways
Jsonobject jsonobj = new Jsonobject ();
Jsonobj.put ("Users", users);
Jsonobj.put ("U", u);
System.out.println (Jsonobj);
{"Users": [{"Password": "1234", "username": "CXL"},{"password": "1234", "username": "Lhl"}],
"U": {"password": "1234", "username": "Lhl"}}
Response.getwriter (). print (jsonobj);
JS Fetch data: alert (data.users[0].username);
alert (data.u[0].username);
Map into JSON format
map<string,object> map = new hashmap<string,object> ();
Map.put ("Users", users);
Map.put ("U", u);
1. Turn into Jsonarray type
Jsonarray JSON = jsonarray.fromobject (map);
System.out.println (Json.tostring ());//
[{"Users": [{"Password": "1234", "username": "CXL"},{"password": "1234", "username": "Lhl"}], "U": {"password": "1234", " Username ":" Lhl "}}]
Response.getwriter (). print (json.tostring);
JS Fetch data: alert (data[0].users[0].username);
2. Turn into Jsonobject type
Jsonobject JSON = jsonobject.fromobject (map);
SYSTEM.OUT.PRINTLN (JSON);//
{"User": [{"Password": "1234", "username": "CXL"},{"password": "1234", "username": "Lhl"}], "U": {"password": "1234", " Username ":" Lhl "}}
Response.getwriter (). print (JSON);
JS Fetch data: alert (data.user[0].username);
JAVA Array,map to JSON string