All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.wicp.tams.common.web.JqueryAssist Maven / Gradle / Ivy

The newest version!
/*
 * **********************************************************************
 * Copyright (c) 2022 .
 * All rights reserved.
 * 项目名称:common
 * 项目描述:公共的工具集
 * 版权说明:本软件属andy.zhou([email protected])所有。
 * ***********************************************************************
 */
package net.wicp.tams.common.web;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.mvel2.templates.TemplateRuntime;

import net.wicp.tams.common.exception.ExceptAll;
import net.wicp.tams.common.exception.ProjectException;

public abstract class JqueryAssist {
	/**
	 * 把List转为Jquery select的model
	 * 
	 * @param fromList
	 *            要转为json的List
	 * @param nameFiled
	 *            label的字段名
	 * @param codeFiled
	 *            code的字段名
	 * @param idName
	 *            属性字段名
	 * @return String
	 *         [{label:'男',value:'M'},{label:'女',value:'F'},{label:'未知',value:''}
	 *         ]
	 * @throws ProjectException
	 * */
	public static String getJsonFromList(List fromList,
			String nameFiled, String codeFiled, String idName)
			throws ProjectException {
		if (CollectionUtils.isEmpty(fromList) || StringUtils.isBlank(nameFiled)
				|| StringUtils.isBlank(codeFiled)) {
			throw new ProjectException(ExceptAll.param_error, "要解析的参数错误");
		}
		if (StringUtils.isBlank(idName)) {
			idName = codeFiled;// 如果缺少ID则把code字段做为ID
		}
		String jsonTempStr = "@['{label:\"'+" + nameFiled + "+'\",value:\"'+"
				+ codeFiled + "+'\",id:\"'+" + idName + "+'\"},']";
		StringBuffer returnBuff = new StringBuffer();
		for (Object object : fromList) {
			returnBuff.append(TemplateRuntime.eval(jsonTempStr, object));
		}
		returnBuff.delete(returnBuff.length() - 1, returnBuff.length());// 去除最后一个“,”
		// returnBuff.append("]}");
		return returnBuff.toString();
	}
}