java listmap 转json_listmap转换成json

展开全部

三、json-lib的JSONArray和List的相互转换。

1.List转JSONArray。

/**

* JSON-Lib List转JSONArray

*/

@Test

public void list2JSONArray() {

//创建一个List

List list = new ArrayList();

JSONModel model = new JSONModel();

model.setAge(10);

model.setName("张三");

model.setDomain("http://www.sojson.com");

list.add(model);

model = new JSONModel();

model.setAge(25);

model.setName("李四");

model.setDomain("http://ping.sojson.com");

list.add(model);

//List 转 JSONArray

JSONArray jsonArray = JSONArray.fromObject(list);

//JSONArray 转 String

String jsonArrayStr = jsonArray.toString();

//输出

System.out.printf("JSON-Lib List转JSONArray:%s",jsonArrayStr);

//JSON-Lib List转JSONArray:

/*

32313133353236313431303231363533e78988e69d8331333363366232[

{

"age": 10,

"domain": "http://www.sojson.com",

"name": "张三"

},

{

"age": 25,

"domain": "http://ping.sojson.com",

"name": "李四"

}

]

*/

}

2.JSONArray转List。

/**

* JSON-Lib JSONArray转List

*/

@SuppressWarnings("unchecked")

@Test

public void jsonArray2List(){

//刚刚的JSON字符串

//[{"age":10,"domain":"http://www.sojson.com","name":"张三"},{"age":25,"domain":"http://ping.sojson.com","name":"李四"}]

String jsonArrayStr = "[{\"age\":10,\"domain\":\"http://www.sojson.com\",\"name\":\"张三\"},{\"age\":25,\"domain\":\"http://ping.sojson.com\",\"name\":\"李四\"}]";

//json字符串转成JSONArray

JSONArray jsonArray = JSONArray.fromObject(jsonArrayStr);

//JSONArray 转 List

List list = JSONArray.toList(jsonArray, JSONModel.class);

//输出

System.out.printf("JSON-Lib JSONArray转List:\n%s",JSONArray.fromObject(list).toString());

/*

JSON-Lib JSONArray转List:

[{"age":10,"domain":"http://www.sojson.com","name":"张三"},{"age":25,"domain":"http://ping.sojson.com","name":"李四"}]

*/

}

这里有一个注意的地方,就是JSONArray.toList()这个方法是过期的。但是不影响使用。

json-lib  介绍到这里就完毕了。然后下面有附件是json-lib 的Jar包。


版权声明:本文为weixin_39530647原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。