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包。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值