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) &NBSp { this.password = password; } }
Normal JavaBean (example of user) 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 ());
Fetching 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);
Fetching data in JS file
alert (data.username);
alert (Data.password);
List 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
Jsonobject jsonobj = jsonobject.fromobject (users) cannot be used directly;
You can use the following methods
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 to fetch data: alert (data.users[0].username);
alert (data.u[0].username);
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.