1. 程式人生 > >Android開發中使用到的 JSONArray、JSONObject

Android開發中使用到的 JSONArray、JSONObject

JSONArray .java

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;

import CommonUtil;

/**
 *  Json物件陣列
 */
public class JSONArray implements Serializable {

	private ArrayList<Object> data;

	public JSONArray() {
		data = new ArrayList<Object>();
	}

	public void add(Object obj) {
		data.add(obj);
	}

	public void delete(int poistion){
		data.remove(poistion);
	}

	public String getString(int index) {
		Object value = get(index);
		if (value == null)
			return null;
		if (value instanceof String) {
			return  CommonUtil.decodeUnicode((String) value);
		} else {
			return CommonUtil.decodeUnicode(value.toString());
		}
	}

	public int getInt(int index) {
		Object value = get(index);
		if (value == null)
			return 0;
		if (value instanceof Integer) {
			return (Integer) value;
		} else {
			try {
				return Integer.parseInt(value.toString());
			} catch (NumberFormatException e) {
				return 0;
			}
		}
	}

	public boolean getBoolean(int index) {
		Object value = get(index);
		if (value == null)
			return false;
		if (value instanceof Boolean) {
			return (Boolean) value;
		} else {
			return false;
		}
	}

	public JSONObject getJSONObject(int index) {
		Object value = get(index);
		if (value == null)
			return null;
		if (value instanceof JSONObject) {
			return (JSONObject) value;
		} else {
			return null;
		}
	}

	public JSONArray getJSONArray(int index) {
		Object value = get(index);
		if (value == null)
			return null;
		if (value instanceof JSONArray) {
			return (JSONArray) value;
		} else {
			return null;
		}
	}

	public boolean isNull(int index) {
		return data.get(index) == null ? true : false;
	}

	public Object get(int index) {
		return data.get(index);
	}

	public ArrayList<Object> getAll() {
		return data;
	}

	public int length() {
		return data.size();
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("[");

		Iterator<Object> itr = data.iterator();
		while (itr.hasNext()) {
			Object obj = itr.next();

			if (obj == null) {
				sb.append("null");
			} else {
				if (obj instanceof JSONArray) {
					sb.append(((JSONArray) obj).toString());
				} else if (obj instanceof JSONObject) {
					sb.append(((JSONObject) obj).toString());
				} else if (obj instanceof Integer) {
					sb.append(((Integer) obj).toString());
				} else if (obj instanceof Boolean) {
					sb.append(((Boolean) obj).toString());
				} else {
					sb.append("\"");
					sb.append(obj.toString());
					sb.append("\"");
				}
			}
			if (itr.hasNext()) {
				sb.append(",");
			}
		}

		sb.append("]");
		return sb.toString();
	}

}
JSONObject.java
import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import CommonUtil;

/**
 * Json物件
 */
public class JSONObject implements Serializable {

	private Map<String, Object> data;

	private String sem = null;

	public JSONObject() {
		data = new LinkedHashMap<String, Object>();
	}

	/**
	 * 
	 * @param text
	 * 
	 */
	public JSONObject(String text) {
		this(text, 0);
	}

	/**
	 * 多種解析器(預留)
	 * 
	 * @param text
	 * @param paser
	 * 
	 */
	public JSONObject(String text, int paser) {
		this();

		if (text != null) {
			try {
				JSONParser parser = new JSONParser(text, this);
				sem = parser.getSEM();
			} catch (Exception e) {
				sem = e.getMessage();
			}
		}
	}

	/**
	 * key如果重複的話,新的value替代老的value
	 * 
	 * @param key
	 * @param value
	 */
	public void add(String key, Object value) {
		data.put(key, value);

	}

	public String getString(String key) {
		Object value = get(key);
		if (value == null) {
			return "";
		} else if (value instanceof String) {
			return CommonUtil.decodeUnicode((String) value);
		} else {
			return CommonUtil.decodeUnicode(value.toString());
		}
	}

	public int getInt(String key) {
		Object value = get(key);
		if (value == null)
			return 0;
		if (value instanceof Integer) {
			return (Integer) value;
		} else {
			try {
				return Integer.parseInt(value.toString());
			} catch (NumberFormatException e) {
				return 0;
			}
		}
	}

	public boolean getBoolean(String key) {
		Object value = get(key);
		if (value == null)
			return false;
		if (value instanceof Boolean) {
			return (Boolean) value;
		} else {
			return false;
		}
	}

	public JSONObject getJSONObject(String key) {
		Object value = get(key);
		if (value == null)
			return null;
		if (value instanceof JSONObject) {
			return (JSONObject) value;
		} else {
			return null;
		}
	}

	public JSONArray getJSONArray(String key) {
		Object value = get(key);
		if (value == null)
			return null;
		if (value instanceof JSONArray) {
			return (JSONArray) value;
		} else {
			return null;
		}
	}

	public boolean isNull(String key) {
		return data.get(key) == null ? true : false;
	}

	public Object get(String key) {
		return data.get(key);
	}

	public Map<String, Object> getAll() {
		return data;
	}

	public int length() {
		return data.size();
	}

	public String getSEM() {
		return sem;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();

		sb.append("{");

		Iterator<Entry<String, Object>> itr = data.entrySet().iterator();

		while (itr.hasNext()) {

			Entry<String, Object> entry = (Entry<String, Object>) itr.next();
			String key = entry.getKey();
			Object value = entry.getValue();

			sb.append("\"");
			sb.append(key);
			sb.append("\": ");

			if (value == null) {
				sb.append("null");
			} else {
				if (value instanceof JSONObject) {
					sb.append(((JSONObject) value).toString());
				} else if (value instanceof JSONArray) {
					sb.append(((JSONArray) value).toString());
				} else if (value instanceof Integer) {
					sb.append(((Integer) value).toString());
				} else if (value instanceof Boolean) {
					sb.append(((Boolean) value).toString());
				} else {
					sb.append("\"");
					sb.append(value.toString());
					sb.append("\"");
				}
			}
			if (itr.hasNext()) {
				sb.append(",");
			}
		}

		sb.append("}");
		return sb.toString();
	}
}

CommonUtil.java

public class CommonUtil {

	public static String decodeUnicode(String theString) {

        char aChar;
        if (isEmpty(theString)) {
            return "";
        }
        int len = theString.length();

        StringBuffer outBuffer = new StringBuffer(len);

        for (int x = 0; x < len; ) {

            aChar = theString.charAt(x++);

            if (aChar == '\\') {

                aChar = theString.charAt(x++);

                if (aChar == 'u') {
                    int value = 0;

                    for (int i = 0; i < 4; i++) {

                        aChar = theString.charAt(x++);

                        switch (aChar) {

                            case '0':

                            case '1':

                            case '2':

                            case '3':

                            case '4':

                            case '5':

                            case '6':

                            case '7':

                            case '8':

                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':

                            case 'b':

                            case 'c':

                            case 'd':

                            case 'e':

                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':

                            case 'B':

                            case 'C':

                            case 'D':

                            case 'E':

                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }

                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')

                        aChar = '\t';
                        
                    else if (aChar == 'r')

                        aChar = '\r';

                    else if (aChar == 'n')

                        aChar = '\n';

                    else if (aChar == 'f')

                        aChar = '\f';

                    outBuffer.append(aChar);

                }

            } else

                outBuffer.append(aChar);

        }

        return outBuffer.toString();

    }

    public static boolean isEmpty(Object o) {
        if (o == null) {
            return true;
        } else if (o instanceof String) {
            return ((String) o).trim().isEmpty() ? true : false;
        } else if (o instanceof JSONObject) {
            return ((JSONObject) o).length() == 0 ? true : false;
        } else if (o instanceof JSONArray) {
            return ((JSONArray) o).length() == 0 ? true : false;
        } else {
            return false;
        }
    }

}