日期:2014-05-16 浏览次数:20414 次
json串示例
[{"id":1,"name":"name1","password":"password1","remark":"remark1"},{"id":2,"name":"name2","password":"password2","remark":"remark2"},{"id":3,"name":"name3","password":"password3","remark":"remark3"}]
主要分为以下几种:
1. 直接构建json串,主要代码;
2. json串 -> java对象;
3. java对象 -> json串/json对象;
4. List<?> -> json串;
5. 对象数组 -> json串。
程序如下:
TestJson.java
import java.util.*;
import net.sf.json.*;
import com.hs.sig.ui.sgms.vo.User;
public class TestJson {
/**
* 初始化userList大小
*/
public static final int USERLISTSIZE = 3;
/**
* 直接构建json串
* @return
*/
public String toJsonString() {
// 初始化 User 对象
User user = null;
List<User> userList = this.initUserList(USERLISTSIZE);
// 构建 json 串
StringBuffer json = new StringBuffer();
json.append("[");
for (int i = 0; i < userList.size(); i++) {
user = userList.get(i);
json.append("{");
json.append("\"id\":\"").append(user.getId()).append("\",");
json.append("\"name\":\"").append(user.getName()).append("\",");
json.append("\"password\":\"").append(user.getPassword()).append("\",");
json.append("\"remark\":\"").append(user.getRemark()).append('"');
json.append("},");
}
json.deleteCharAt(json.lastIndexOf(","));
json.append("]");
//System.out.println("直接构建 json 串结果:" + json.toString());
return json.toString();
}
/**
* json串 -> java对象
* @return
*/
public String jsonToObject() {
StringBuffer info = new StringBuffer();
if(this.isArray(this.toJsonString())){
JSONArray jSONArray = JSONArray.fromObject(this.toJsonString());
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setArrayMode(JsonConfig.MODE_LIST);
jsonConfig.setRootClass(User.class);
List<User> userList = (List<User>) JSONSerializer.toJava(jSONArray, jsonConfig);
User user = null;
for (int i = 0; i < userList.size(); i++) {
user = userList.get(i);
info.append("user" + (i + 1) + ".id=" + user.getId());
info.append(",user" + (i + 1) + ".name=" + user.getName());
info.append(",user" + (i + 1) + ".password=" + user.getPassword());
info.append(",user" + (i + 1) + ".remark=" + user.getRemark());
info.append("\n");
}
//System.out.println("json串 -> java对象:" + info.toString());
}
return info.toString();
}
/**
* java对象 -> json串/json对象
* @return
*/
public String objectToJson() {
// 初始化一个user对象
User user = null;
List<User> userList = this.initUserList(USERLISTSIZE);
user = userList.get(0);
// 转换user对象的配置
JsonConfig jsonConfig = new JsonConfig();
// 过滤对象中不需要转化的属性
jsonConfig.setExcludes(new String[]{"id"});
// 将对象user转化为json串
JSONArray jsonArray = JSONArray.fromObject(user, jsonConfig);
//jsonArray = JSONArray.fromObject(user);
// 转化为json对象
//JSONObject jsonObject = JSONObject.fromObject(user, jsonConfig);
//jsonObject = JSONObject.fromObject(user);
return jsonArray.toString();
}
/**
* List<User> -> json