java 封装解析 Json数据。

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.led.image.TransformUtils;
import com.ledsystem.util.EncodingDetect;

/**
 * @deprecated锛氳В鏋怞son鏁扮粍
 * @author Gary huang 
 * @since : 1.0.0 
 * */

@SuppressWarnings("unchecked")
public class JsonArrayUtils {
	
	private List<NodeObject> nodes = null ;
	
	public JsonArrayUtils(String json){
		try {
			JSONArray jsonArray = JSONArray.parseArray(json);
			nodes = parseNodes( jsonArray ) ;
		} catch (Exception e) {
			e.printStackTrace() ; 
		}
	}
	
	List<NodeObject> parseNodes(JSONArray array){
		List<NodeObject> nodes = new Vector<NodeObject>();
		int size = array.size() ;
		for (int i = 0; i < size; i++) {
			try {
				JSONObject json = array.getJSONObject(i);
				nodes.add(parseNodeObject(json)) ;
			} catch (Exception e) {
				e.printStackTrace() ;
			}
			
		} 
		return nodes ; 
	}
	
	NodeObject parseNodeObject(JSONObject json){
		NodeObject node = new NodeObject();
		Iterator<String> key = json.keySet().iterator() ; 
		while(key.hasNext()){
			String keyName = TransformUtils.toString(key.next());
			try {
				Object value = json.get( keyName ) ; 
				if(null == value){
					continue ;
				} 
				if(value instanceof JSONObject){
					node.put( keyName , parseNodeObject((JSONObject) value ) ) ;  
				}else if(value instanceof JSONArray){
					node.put( keyName , parseNodes((JSONArray) value ) ) ;  
				}else{
					node.put( keyName , value ) ;
				}
			} catch (Exception e){
				e.printStackTrace() ;
			}
		}
		return node ;
	}
	
	public List<NodeObject> getNodes() {
		return nodes;
	}
	
	public NodeObject getNode() {
		return nodes.get(0) ; 
	}
	
	public static class NodeObject{
		private Map<String, Object> datas = new HashMap<String, Object>();
		
		public void put(String key , Object value){
			datas.put(key, value) ;
		}
		
		public Object get(String key){
			return datas.get(key) ;  
		}
		
		@Override
		public String toString() {
			return datas.toString(); 
		}
	}
	
	public static class NodeItem{
		
		private String key ;
		
		private Object value ;

		public String getKey() {
			return key;
		}

		public void setKey(String key) {
			this.key = key;
		}

		public Object getValue() {
			return value;
		}

		public void setValue(Object value) {
			this.value = value;
		} 
		
		public NodeObject getNode(){
			return (NodeObject)this.value;
		}
		
		public List<NodeObject> getNodes(){
			return ((List<NodeObject>)this.value);
		}
		
		@Override
		public String toString() {
			return "key:" + key 
					+ "value:" + value ; 
		}
	}
}

你可能感兴趣的:(java)