JSON是一种轻量级的数据交换格式,非常适合于服务器与 JavaScript 的交互。是移动开发中数据客户端和服务器端数据交互的不二选择; 尤其是现在HTML5的流行,更显着使用Json 完成数据交互的重要性.
在这里, 我将演示一下Java基本数据转换为Json代码
Json必需包
如果不想自己下载jar 可以使用这个demo
1.List集合转换成json代码
List<Person> list = new ArrayList<Person>();
list.add(new Person(0,"nagi_ho", 20,"海淀"));
list.add(new Person(1, "eson_ho", 21,"朝阳"));
JSONArray jsonList = JSONArray.fromObject(list);
System.out.println("1.List集合转换成json代码====>" + jsonList.toString());
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[] { "btbu", "b" });
map.put("func", "function(i){ return this.arr; }");
JSONObject jsonMap = JSONObject.fromObject(map);
System.out.println("2.Map集合转换成json代码====>"+jsonMap.toString());
3.Set集合转换成json代码
Set<Person> set = new HashSet<Person>();
set.add(new Person(0, "nagi_ho", 20,"信管112"));
set.add(new Person(1, "eson_ho", 22,"电商112"));
JSONArray jsonArray4 = JSONArray.fromObject(set);
System.out.println("3.Set集合转换成json代码====>" +jsonArray4.toString());
4.Bean转换成json代码
JSONObject jsonObject = JSONObject.fromObject(new Person(1, "信管112", 22,"btbu"));
System.out.println("4.Bean转换成json代码====>"+jsonMap.toString());
5.数组转换成json代码
boolean[] boolArray = new boolean[] { true, false, true };
String[] stringArray = new String[] {"信管111","信管112", "电商111", "电商112"};
JSONArray boolArray1 = JSONArray.fromObject(boolArray);
JSONArray jsonArray2 = JSONArray.fromObject(stringArray);
System.out.println("5.数组转换成json代码====>"+boolArray1.toString());
System.out.println("5.数组转换成json代码====>"+jsonArray2.toString());
6.一般数据转换成json代码
JSONArray jsonArray3 = JSONArray.fromObject("[‘json‘,‘is‘,‘easy‘]" );
System.out.println("6.一般数据转换成json代码====>"+jsonArray3.toString());
运行结果:
1.List集合转换成json代码====>[{"address":"海淀","age":20,"id":0,"name":"nagi_ho"},{"address":"朝阳","age":21,"id":1,"name":"eson_ho"}]
2.Map集合转换成json代码====>{"arr":["btbu","b"],"int":1,"name":"json","func":function(i){ return this.arr; },"bool":true}
3.Set集合转换成json代码====>[{"address":"电商112","age":22,"id":1,"name":"eson_ho"},{"address":"信管112","age":20,"id":0,"name":"nagi_ho"}]
4.Bean转换成json代码====>{"arr":["btbu","b"],"int":1,"name":"json","func":function(i){ return this.arr; },"bool":true}
5.数组转换成json代码====>[true,false,true]
5.数组转换成json代码====>["信管111","信管112","电商111","电商112"]
6.一般数据转换成json代码====>["json","is","easy"]
当然我相信大家对这个json 格式不满意, 那么我们使用json的格式化工具Hison( 点击下载)
[
{
"address":"北京",
"age":20,
"id":0,
"name":"nagi"
},
{
"address":"北京",
"age":21,
"id":1,
"name":"nag1"
},
{
"address":"北京",
"age":22,
"id":2,
"name":"nag2"
},
{
"address":"北京",
"age":23,
"id":3,
"name":"nag3"
},
{
"address":"北京",
"age":24,
"id":4,
"name":"nag4"
}
]
这样是不是看起来很爽了, 试一试吧,
如果觉得对你有用 给个赞吧~
原文地址:http://blog.csdn.net/u012173245/article/details/44036427