json 트 리 구조 (자바)

6573 단어 자바 기초 학습
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 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 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 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 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 
	 * @param objs
	 * @param pidAttr
	 * @param idAttr
	 * @return
	 * @throws Exception
	 */
	public static  String treeJson(long pid , List objs, StringBuilder builder, String pidAttr, String idAttr, String labelAttr) throws Exception {
		if (objs.size() == 0){
			return "{\"children\":[]}";
		}
		for(Iterator 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 
	 * @param id
	 * @param objs
	 * @return
	 * @throws Exception 
	 */
	private static  boolean isHasChildren(long id , List objs, String pidAttr) throws Exception{
		for(T t : objs){
			long pid = getLong(t, pidAttr);
			if(pid == id){
				return true;
			}
		}
		return false;
	}
	
	private static  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  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 lists = new ArrayList();
		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);
	}
}

좋은 웹페이지 즐겨찾기