String字符串轉成List對象

數據:
[{"groupidx":"1","groupname":"色牢固要求","cname":"耐光","ccidx":"1","cunit":"spf","cvalue":"2","crange":"2"},
{"groupidx":"1","groupname":"色牢固要求","cname":"耐汗","ccidx":"2","cunit":"米","cvalue":"3","crange":"1"},
{"groupidx":"2","groupname":"物性要求","cname":"耐水級","ccidx":"3","cunit":"米","cvalue":"4","crange":"21"},

{"groupidx":"2","groupname":"物性要求","cname":"通氣度","ccidx":"4","cunit":"ml/cm","cvalue":"2","crange":"1"}]

String json = "[{"groupidx":"1","groupname":"色牢固要求","cname":"耐光","ccidx":"1","cunit":"spf","cvalue":"2","crange":"2"},
{"groupidx":"1","groupname":"色牢固要求","cname":"耐汗","ccidx":"2","cunit":"米","cvalue":"3","crange":"1"},
{"groupidx":"2","groupname":"物性要求","cname":"耐水級","ccidx":"3","cunit":"米","cvalue":"4","crange":"21"},
{"groupidx":"2","groupname":"物性要求","cname":"通氣度","ccidx":"4","cunit":"ml/cm","cvalue":"2","crange":"1"}]";
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
//去除兩端方括號
json = json.replaceAll("[\\[\\]]", "");
//第一次分割
String[] splitArray = json.split("},");
for(int i=0; i<splitArray.length;i++) {
	//去除大括號,好方法去除大括號就用了子串的方式
	if(i==splitArray.length-1) {
		splitArray[i]=splitArray[i].substring(1, splitArray[i].length()-1);
	}else {
		splitArray[i]=splitArray[i].substring(1, splitArray[i].length());
	}			
	Map<String,Object> map = new HashMap<String,Object>();
	//第二次分割
	String[] mapArray = splitArray[i].split(",");
	for(int j=0 ;j<mapArray.length ;j++) {
		String str = mapArray[j].replaceAll("\"", "");
		//第三次分割,爲了防止value爲空,下面加了一個長度判斷
		String[] keyValue = str.split(":");
		if(keyValue.length==2) map.put(keyValue[0], keyValue[1]);
		else map.put(keyValue[0], "");
	}
	list.add(map);
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章