JSONObject.fromObject(map)(JSON与JAVA数据的转换)

来源:互联网 发布:数据库王珊第5版百度云 编辑:程序博客网 时间:2024/06/01 09:18
JSON与JAVA数据的转换(JSON 即 JavaScript ObjectNatation,它是一种轻量级的数据交换格式,非常适合于服务器与 JavaScript的交互。

上一篇文章中有这么一句,是后台的封装数据。
JSONObjectjo = JSONObject.fromObject(map);
常见的java代码转换成json


1. List集合转换成json代码

List list = newArrayList();

list.add( "first" );

list.add( "second" );

JSONArray jsonArray2 =JSONArray.fromObject( list );

2. Map集合转换成json代码

Map map = newHashMap();

map.put("name","json");

map.put("bool",Boolean.TRUE);

map.put("int", newInteger(1));

map.put("arr", new String[] {"a", "b" });

map.put("func", "function(i){return this.arr[i]; }");

JSONObject json =JSONObject.fromObject(map);

3. Bean转换成json代码

JSONObject jsonObject =JSONObject.fromObject(new JsonBean());

4. 数组转换成json代码

boolean[] boolArray = newboolean[] { true, false, true };

JSONArray jsonArray1 =JSONArray.fromObject(boolArray);

5. 一般数据转换成json代码

JSONArray jsonArray3 =JSONArray.fromObject("['json','is','easy']" );

1 0
原创粉丝点击