首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

Json对象与会合对象互转

2013-03-21 
Json对象与集合对象互转下面来看看Json对象是如何与集合对象互转package com.jsonimport net.sf.json.JSO

Json对象与集合对象互转
下面来看看Json对象是如何与集合对象互转


package com.json;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class TestJson {

// json字符串转
private static String diskListContent = "[{"n1":"asd","n2":22,"n3":"45.40GB","
+ ""n4":"qwerty","n5":"asd",},"
+ "{"n1":"local","
+ ""n2":1,"n3":"279.40GB","n4":"ST3300656SS","n5":"\\/devm\\/d0"}]";

/***
* json字符串转java List
*
* @param rsContent
* @return
* @throws Exception
*/
private static List<Map<String, String>> jsonStringToList(String rsContent)
throws Exception {
JSONArray arry = JSONArray.fromObject(rsContent);
System.out.println("json字符串内容如下");
System.out.println(arry);
List<Map<String, String>> rsList = new ArrayList<Map<String, String>>();
for (int i = 0; i < arry.size(); i++) {
JSONObject jsonObject = arry.getJSONObject(i);
Map<String, String> map = new HashMap<String, String>();
for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();) {
String key = (String) iter.next();
String value = jsonObject.get(key).toString();
map.put(key, value);
}
rsList.add(map);
}
return rsList;
}

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
List<Map<String, String>> list1 = jsonStringToList(diskListContent);
System.out.println("json字符串成map");
for (Map<String, String> m : list1) {
System.out.println(m);
}
System.out.println("map转换成json字符串");
for (Map<String, String> m : list1) {
JSONArray jsonArray = JSONArray.fromObject(m);
System.out.println(jsonArray.toString());
}
System.out.println("list转换成json字符串");
JSONArray jsonArray2 = JSONArray.fromObject(list1);
System.out.println(jsonArray2.toString());
}
}


以上代码复制即可运行使用

热点排行
Bad Request.