//创建JSONObject对象 JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "kevin"); jsonObject.put("Max.score", new Integer(100)); jsonObject.put("Min.score", new Integer(50)); jsonObject.put("nickname", "picglet");
System.out.println("jsonObject==>"+jsonObject);
jsonObject==>{"name":"kevin","Max.score":100,"Min.score":50,"nickname":"picglet"}
boolean isArray = jsonObject.isArray();
boolean isEmpty = jsonObject.isEmpty();
boolean isNullObject = jsonObject.isNullObject();
System.out.println("isArray:"+isArray+" isEmpty:"+isEmpty+" isNullObject:"+isNullObject);
//添加属性
jsonObject.element("address", "swap lake");
System.out.println("添加属性后的对象==>"+jsonObject);
//返回一个JSONArray对象
JSONArray jsonArray = new JSONArray();
jsonArray.add(0, "this is a jsonArray value");
jsonArray.add(1,"another jsonArray value");
jsonObject.element("jsonArray", jsonArray);
JSONArray array = jsonObject.getJSONArray("jsonArray");
System.out.println("返回一个JSONArray对象:"+array);
1. List集合转换成json代码
List list = new ArrayList();
list.add( "first" );
list.add( "second" );
JSONArray jsonArray2 = JSONArray.fromObject( list );
2. Map集合转换成json代码
Map map = new HashMap();
map.put("name", "json");
map.put("bool", Boolean.TRUE);
map.put("int", new Integer(1));
map.put("arr", new String[] { "a", "b" });
map.put("func", "function(i){ return this.arr[i]; }");
JSONObject json = JSONObject.fromObject(map);
还有一个就是在工作中,前端form 表单元素提交,与后台交互一个经常用到的就是fromObject(Object object)
var bean = $('#EditFormApp').serializeArray();
var r = $('#EditFormApp').form('validate');
if (r) {
var beanJson = convertToJson(bean);
var beanJsonString = JSON.stringify(beanJson);
$.post(baseurl + 'platform/applicationLiaAction/updatestatus.json',
{
jsonString : beanJsonString
}, function(status) {
if (status.flag == "success") {
$.messager.show({
title : '提示',
msg : "保存成功!"
});
} else {
$.messager.show({
title : '提示',
msg : "保存失败!"
});
}
dataGrid.load();
});
}
后台可能通过个方法
String jsonString = request.getParameter("jsonString");
jsonString 的格式就是 String json = "{id:'1001',name:'张三',age:'22'}";
JSONObject jsonObject = JSONObject.fromObject(jsonString);
JSONUtils.getMorpherRegistry().registerMorpher(
new DateMorpher(new String[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "yyyy-MM-dd't'HH:mm:ss" }, new Date()));
ApplicationInfo bean = (ApplicationInfo) JSONObject.toBean(jsonObject, ApplicationInfo.class);fromObject(Object object, JsonConfig jsonConfig)
FaiDataTree faiDataTree = dataTreeList.get(i);
JSONObject jsonObject =JSONObject.fromObject(
faiDataTree
,jsonConfig)
其中的,是一些初始化的注册事件,信息详见api
jsonConfig
一个在线 的API
http://json-lib.sourceforge.net/apidocs/jdk15/index.html