1. 程式人生 > >JSONArray轉List>頁面取值

JSONArray轉List>頁面取值

這是簡單的單個鍵值方式的,本文是一組2*2的4張圖片展示存在資料庫的jsonarray格式取出在頁面展示的示例:

1.publicutil類

public class PublicUtil {
	/**
	 * jsonArray轉List<HashMap<String,String>>
	 * @param json格式字串;
	 * */
	//jsonArray格式
	/**
	 	[ {"pic":"http://address4","order":"4"},
		 {"pic":"http://address3","order":"3"},
		 {"pic":"http://address2","order":"2"},
		 {"pic":"http://address1","order":"1"}]
	 */
	public static List<HashMap<String,String>> getPics(String pics) {
		List<HashMap<String,String>>res = new ArrayList<HashMap<String,String>>();
		if(pics==null||pics.equals("")||!pics.startsWith("[")||!pics.endsWith("]")){
			return res;
		}
		JSONArray jsons = JSONArray.fromObject(pics);
		JSONObject json = null;
		HashMap<String,String>map = null;
		String pic = null;
		String order = null;
		for(int i=0;i<jsons.size();i++){
			json = jsons.getJSONObject(i);
			pic = json.getString("pic");
			order = json.getString("order");
			if(pic!=null&&!"".equals(pic)&&order!=null&&!"".equals(order)){
				map = new HashMap<String,String>();
				map.put("order",order);
				map.put("pic",pic.indexOf(".jpg")!=-1?pic:pic+".jpg");
				res.add(map);
			}
		}
		//給獲取的list按照order欄位排序
		Collections.sort(res, new Comparator<HashMap<String,String>>() {
			@Override
			public int compare(HashMap<String, String> o1,HashMap<String, String> o2) {
				int order1 = Integer.parseInt(o1.get("order"));
				int order2 = Integer.parseInt(o2.get("order"));
				System.out.println(order1<order2);
				if (order1<order2) {
					return -1;
				}else{
					return 0;
				}
			}
		});
		return res;
	}
}	

2.Controller類

@Controller
public class UserController {
	@RequestMapping("add")
	public ModelAndView addInfo(HttpServletRequest reqeust,HttpServletResponse response){
		ModelAndView res=new ModelAndView("add");
		res.addObject("name", "塔睿");
		//json開始,示例
		String rels="[{\"pic\":\"地址1\""
				+ ",\"order\":\"9\"},{\"pic\":\"地址2\""
				+ ",\"order\":\"8\"},{\"pic\":\"地址3\",\"order\":\"7\"}]";
		List<HashMap<String, String>> list= PublicUtil.getPics(rels);
		res.addObject("list", list);
		//json結束
		//c:forTokens開始
		String tags="a~b~c~d~~e";
		res.addObject("tags", tags);
		//c:forTokens結束
		return res;		
	}
	/*
	 * 可以使用如下方法收集資料並生成相應的JSON字串
	 */
	@RequestMapping("one")
	public void firstOne(){
		//宣告一個hash物件並新增資料
		Map params=new HashMap();
		params.put("name", "名稱1");
		params.put("age", "12");
		/*params.put("name", "名稱2");
		params.put("age", "13");*/
		//JSONArray檢查物件型別呼叫正確的工廠方法
		//宣告JSONArray物件並輸入json字串
		JSONArray array=JSONArray.fromObject(params);
		//輸出	[{"age":"12","name":"名稱1"}]
		System.out.println(array.toString());
	}
}

3.jsp頁面

<%@ page language="java" import="java.util.Map" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
Map<String,String> menus=(Map<String,String>)request.getAttribute("menus");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
<link href="http://libs.baidu.com/bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
<script src="http://libs.baidu.com/bootstrap/2.3.2/js/bootstrap.min.js"></script>
</head>
<body>
	<form>
		獲取:<input type="text" name="name" value="${name }"/><br/>
		<!-- c:foreach遍歷List<HashMap<String, String>> -->
		<c:forEach items="${list }" var="lists">
			<span>${lists.order }</span>
			<input type="text" value="${lists.pic }"/><br/>
		</c:forEach>
		<!-- c:forTokens用法,delims按照這個進行分割,迴圈的次數也由‘~’個數決定 -->
		<c:forTokens items="${tags }" delims="~" var="tag">
			<input type="text" value="${tag }"/><br/>
		</c:forTokens>
	</form>
</body>
</html>