`
rockyuse
  • 浏览: 191868 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

json转树状结构(java)

 
阅读更多
package cn.info.platform.test;

import java.io.IOException;
import java.lang.String;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import org.omg.CORBA.PRIVATE_MEMBER;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests;

import cn.info.platform.dao.FaqDao;
import cn.info.platform.entity.Faq;
import cn.info.platform.entity.FaqType;

/**
 * @author Rocky
 */
@ContextConfiguration("classpath:spring-*.xml")
public class FaqTest extends AbstractJUnit38SpringContextTests {
	@Autowired
	private FaqDao faqDao;

	public void testGetByID() {
		ArrayList<FaqType> faqTypeList = faqDao.faqTypeList();
		
		String nodeTree = getNodeTree(faqTypeList, 0);
		System.out.println(nodeTree);
		
		String nodeTreeSql = getNodeTreeSql(0);
		System.out.println(nodeTreeSql);
		
	}
	
	
	private String getNodeTreeSql(int fid){
		StringBuffer nodeStr = new StringBuffer("{");
		nodeStr = nodeTreeSql(nodeStr, 0);
		nodeStr = nodeStr.deleteCharAt(nodeStr.length() - 1);
		return nodeStr.toString();
	}
	
	
	private StringBuffer nodeTreeSql(StringBuffer nodeTreeStr, int fid){
		ArrayList<FaqType> faqTypeList = faqDao.faqTypeByFid(fid);
		int len = faqTypeList.size();
		if(len > 0){
			nodeTreeStr.append("\"children\":[");
			for(int i = 0; i < len; i++){
				nodeTreeStr.append("{\"name\":\"" + faqTypeList.get(i).getName() + "\",");
				nodeTreeStr = nodeTreeSql(nodeTreeStr, faqTypeList.get(i).getId());
			}
			nodeTreeStr.deleteCharAt(nodeTreeStr.length() - 1);
			nodeTreeStr.append("]},");
		}else{
			nodeTreeStr.deleteCharAt(nodeTreeStr.length() - 1);
			nodeTreeStr.append("},");
		}
		return nodeTreeStr;
	}
	
	
	private String getNodeTree(ArrayList<FaqType> faqTypeList, int fid){
		StringBuffer nodeStr = new StringBuffer("{");
		nodeStr = nodeTree(nodeStr, 0, faqTypeList);
		nodeStr = nodeStr.deleteCharAt(nodeStr.length() - 1);
		return nodeStr.toString();
	}
	
	private StringBuffer nodeTree(StringBuffer nodeTreeStr, int fid, ArrayList<FaqType> faqTypeList){
		Boolean hasChildren = false;
		StringBuffer nodeTr = new StringBuffer();
		for(int i = 0; i < faqTypeList.size(); i++){
			if(faqTypeList.get(i).getFid() == fid){
				nodeTr.append("{\"name\":\"" + faqTypeList.get(i).getName() + "\",");
				nodeTr = nodeTree(nodeTr, faqTypeList.get(i).getId(), faqTypeList);
				hasChildren = true;
			}
		}
		if(hasChildren == false){
			nodeTreeStr.deleteCharAt(nodeTreeStr.length() - 1);
			nodeTreeStr.append("},");
		}else{
			nodeTr.deleteCharAt(nodeTr.length() - 1);
			nodeTreeStr.append("\"children\":[").append(nodeTr).append("]},");
		}
		return nodeTreeStr;
	}
}

 

 

Json2Tree

package cn.info.platform.test;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import cn.info.platform.entity.FaqType;


/**
 * Json字符串工具类
 * 
 * @author luojiang2
 * 
 */
public class Json2Tree {

	/**
	 * 根据id,pid和树要显示的属性生成树的Json字符串
	 * 
	 * @param <T>
	 * @param objs
	 * @param pidAttr
	 * @param idAttr
	 * @return
	 * @throws Exception
	 */
	public static <T> String treeJson(long pid , List<T> objs, StringBuilder builder, String pidAttr, String idAttr, String labelAttr) throws Exception {
		if (objs.size() == 0){
			return "{\"children\":[]}";
		}
		for(Iterator<T> iter = objs.iterator(); iter.hasNext();) {
			T t = iter.next();
			long id = getLong(t, idAttr);
			long temp_pid = getLong(t, pidAttr);
			String label = getValue(t, labelAttr);
			if(pid == Long.MAX_VALUE){
				break;
			}
			if(temp_pid == pid){
				builder.append("{\"id\":\"").append(id).append("\",");
				builder.append("\"name\":\"").append(label).append("\",");
				if(isHasChildren(id, objs, pidAttr)) {
					builder.append("\"children\":[");
					treeJson(id, objs, builder, pidAttr, idAttr, labelAttr);
					builder.append("]},");
				}else{
					builder.deleteCharAt(builder.length() - 1).append("},");
				}
			}
		}
		builder.deleteCharAt(builder.length() - 1);
		return builder.toString();
	}
	
	/**
	 * 判断给定id节点是否有孩子节点
	 * @param <T>
	 * @param id
	 * @param objs
	 * @return
	 * @throws Exception 
	 */
	private static <T> boolean isHasChildren(long id , List<T> objs, String pidAttr) throws Exception{
		for(T t : objs){
			long pid = getLong(t, pidAttr);
			if(pid == id){
				return true;
			}
		}
		return false;
	}
	
	private static <T> long getLong(T t, String attrName) throws Exception {
		Field field = t.getClass().getDeclaredField(attrName);
		if (!field.isAccessible()) {
			field.setAccessible(true);
		}
		Object value = field.get(t);
		if (value == null){
			return Long.MAX_VALUE;
		}else{
			return Long.parseLong(value.toString());
		}
	}

	private static <T> String getValue(T t, String attrName) throws Exception {
		Field field = t.getClass().getDeclaredField(attrName);
		if (!field.isAccessible()) {
			field.setAccessible(true);
		}
		Object value = field.get(t);
		if (value == null){
			return "\"\"";
		}else{
			return value.toString();
		}
	}

	public static void main(String[] args) throws Exception {
		List<FaqType> lists = new ArrayList<FaqType>();
		FaqType a1 = new FaqType();
		FaqType a2 = new FaqType();
		FaqType a3 = new FaqType();
		FaqType a4 = new FaqType();
		FaqType a5 = new FaqType();
		FaqType a6 = new FaqType();

		a1.setFid(-1);
		a1.setId(1);
		a1.setName("a");

		a2.setFid(1);
		a2.setId(2);
		a2.setName("b");

		a3.setFid(1);
		a3.setId(3);
		a3.setName("c");

		a4.setFid(2);
		a4.setId(4);
		a4.setName("d");

		a5.setFid(3);
		a5.setId(5);
		a5.setName("e");

		a6.setFid(5);
		a6.setId(6);
		a6.setName("f");

		lists.add(a1);
		lists.add(a2);
		lists.add(a3);
		lists.add(a4);
		lists.add(a5);
		lists.add(a6);
		
		String results = treeJson( -1,lists, new StringBuilder(), "fid", "id", "name");
		System.out.println(results);
	}
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics