JSONArray转List>页面取值

这是简单的单个键值方式的,本文是一组2*2的4张图片展示存在数据库的jsonarray格式取出在页面展示的示例:

1.publicutil类

public class PublicUtil {
	/**
	 * jsonArray转List>
	 * @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> getPics(String pics) {
		List>res = new ArrayList>();
		if(pics==null||pics.equals("")||!pics.startsWith("[")||!pics.endsWith("]")){
			return res;
		}
		JSONArray jsons = JSONArray.fromObject(pics);
		JSONObject json = null;
		HashMapmap = null;
		String pic = null;
		String order = null;
		for(int i=0;i();
				map.put("order",order);
				map.put("pic",pic.indexOf(".jpg")!=-1?pic:pic+".jpg");
				res.add(map);
			}
		}
		//给获取的list按照order字段排序
		Collections.sort(res, new Comparator>() {
			@Override
			public int compare(HashMap o1,HashMap o2) {
				int order1 = Integer.parseInt(o1.get("order"));
				int order2 = Integer.parseInt(o2.get("order"));
				System.out.println(order1

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> 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 menus=(Map)request.getAttribute("menus");
%>




Insert title here





	
获取:
${lists.order }

你可能感兴趣的:(Java,SpringMVC)