1、依赖的包

非常有用的参考:

(1)json在线转换器:http://json.parser.online.fr/

(2)json介绍:http://www.json.org/json-zh.html

2、普通JavaBean

(1)基本JavaBean

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;
}
}

(2)转化成JSONArray

User user = new User();
user.setUsername("lp");
user.setPassword("1234");
JSONArray json = JSONArray.fromObject(user);
System.out.println(json);
//结果:[{"password":"1234","username":"lp"}]

(3)转化成JSONObject

User user = new User();
user.setUsername("lp");
user.setPassword("1234");
JSONObject json = JSONObject.fromObject(user);
System.out.println(json);
//结果;{"password":"1234","username":"lp"}

 

3、List<User>

(1)转化成JSONArray

List<User>users = new ArrayList<>();
User user = new User();
user.setUsername("lp");
user.setPassword("1234");
User userSecond = new User();
userSecond.setUsername("ch");
userSecond.setPassword("4567");
users.add(user);
users.add(userSecond);
JSONArray json = JSONArray.fromObject(users);
System.out.println(json);
//结果:[{"password":"1234","username":"lp"},{"password":"4567","username":"ch"}]

(2)转化成JSONObject

不可以直接通过JSONObject jsonObj = JSONObject.fromObject(users);进行

可以通过如下方式:

JSONObject json = new JSONObject();
json.put("users", users);
json.put("userSecond", userSecond);
System.out.println(json);
//结果:{"users":[{"password":"1234","username":"lp"},{"password":"4567","username":"ch"}],"userSecond":{"password":"4567","username":"ch"}}

  

4、Map

(1)转化成JSONArray

Map<String, Object>map = new HashMap<String, Object>();
map.put("users", users);
map.put("user", user);
JSONArray json = JSONArray.fromObject(map);
System.out.println(json);
//结果:[{"users":[{"password":"1234","username":"lp"},{"password":"4567","username":"ch"}],"user":{"password":"1234","username":"lp"}}]

(2)转化成JSONObject

Map<String, Object>map = new HashMap<String, Object>();
map.put("users", users);
map.put("user", user);
JSONObject json = JSONObject.fromObject(map);
System.out.println(json);
//结果:{"users":[{"password":"1234","username":"lp"},{"password":"4567","username":"ch"}],"user":{"password":"1234","username":"lp"}}

来源:http://blog.sina.com.cn/s/blog_a15aa56901017i2x.html

05-11 00:59