package cn.com.test;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JSONObjectStudy {
/**
* @param args
*/
public static void main(String[] args) {
User user = new User("10", "zhang", "123456");
convertFromVO(user); // 从实体转向json
}
/**
* json自己添加
*/
public static void json() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name1", "zhang");
jsonObject.put("name2", "zhang");
jsonObject.put("name3", "zhang");
System.out.println(jsonObject);
}
/**
* 对象转换文本
*/
public static void convertFromVO(User user) {
JSONObject json = JSONObject.fromObject(user);
System.out.println("convertFromVO\t"+json+"\n-------");
convertToVO(json.toString()); // 转成对象
}
/**
* 文本转换对象
*
* @param text
*/
public static void convertToVO(String text) {
JSONObject json = JSONObject.fromObject(text);
User user = (User) JSONObject.toBean(json, User.class);
System.out.println("convertToVO\t"+"id:"+user.getId()+"\n-------");
//加入集合再转换
List<User> list=new ArrayList<User>();
list.add(user);
convertFromList(list);
}
/**
* 从集合转换
*/
public static void convertFromList(List<User> list) {
JSONArray jsonArray = new JSONArray();
jsonArray = JSONArray.fromObject(list);
System.out.println("convertFromList\t"+jsonArray.toString()+"\n-------");
convertToList(jsonArray.toString()); //再转换成list
}
/**
* 文本转换成集合
* @param text
*/
public static void convertToList(String text) {
JSONArray jsonArray = new JSONArray();
jsonArray = JSONArray.fromObject(text);
List<User> list=(List<User>)JSONArray.toList(jsonArray,User.class);
System.out.println("convertToList\t"+list.get(0).getId()+"\n-------");
}
}