package com.json.parse;

import java.util.*;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.bean.User;

public class UserGeneJson {
public static void main(String[] args) {
List<User> userlist = generateList();
System.out.println(listToJson(userlist));
}

private static String listToJson(List<User> userlist) {
JSONArray jsonArray = new JSONArray();

for (User user : userlist) {
JSONObject jsonObject = new JSONObject();
// 向jsonObject添加属性对
jsonObject.accumulate("age", user.getAge());
jsonObject.accumulate("username", user.getUsername());
jsonObject.accumulate("password", user.getPassword());

// 使用JSONArray存放favoriteList
List<String> favoriteList = user.getFavoriteList();

JSONArray favoriteArray = new JSONArray();
for (String favotite : favoriteList) {
favoriteArray.add(favotite);
}

jsonObject.accumulate("favoriteList", favoriteArray);

// 将jsonObject放入jsonArray
jsonArray.add(jsonObject);

}

return jsonArray.toString();
}

private static List<User> generateList() {
List<User> userList = new ArrayList<User>();

List<String> favoriteList = new ArrayList<String>();
favoriteList.add("美食");
favoriteList.add("美酒");
favoriteList.add("美景");
favoriteList.add("美女");

userList.add(new User(18, "周义", "admin", favoriteList));
userList.add(new User(28, "老王", "admin", favoriteList));
userList.add(new User(38, "老周", "admin", favoriteList));

return userList;
}
}


package com.bean;

import java.util.List;
import java.util.Map;

public class User {
private int age;
private String username;
private String password;
private List<String> favoriteList;
private Map<Integer, String> feeling;

public User(int age, String username, String password,
List<String> favoriteList) {
super();
this.age = age;
this.username = username;
this.password = password;
this.favoriteList = favoriteList;
}

public User(int age, String username, String password,
List<String> favoriteList, Map<Integer, String> feeling) {
super();
this.age = age;
this.username = username;
this.password = password;
this.favoriteList = favoriteList;
this.feeling = feeling;
}

public Map<Integer, String> getFeeling() {
return feeling;
}

public void setFeeling(Map<Integer, String> feeling) {
this.feeling = feeling;
}

public User() {
super();
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

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

public List<String> getFavoriteList() {
return favoriteList;
}

public void setFavoriteList(List<String> favoriteList) {
this.favoriteList = favoriteList;
}

@Override
public String toString() {
return "User [age=" + age + ", username=" + username + ", password="
+ password + ", favoriteList=" + favoriteList + ", feeling="
+ feeling + "]";
}

}