`
ahuango
  • 浏览: 55606 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

一个简单的JSON 数据格式转换类

阅读更多
在项目中使用JSON格式传输数据时经常碰到数据格式的转换, 一般可以使用Json.org的lib, 以及一些第三方的框架来完成。 但是如果只是一个简单的项目,而且json的使用并不多的情况下,可以自己写一个类来处理。
在代码中,我让我的Json类继承与TreeMap,这样可以利用Map与Json格式的相似性,节省一些代码量和定义数据结构的烦恼。 Json结构在前台支持基本数据类型和数据类型, 所以这样的数据类型在js中也是有效的:
{'1':'ha','2':'ch','3':['list1','list2','list3']}

依据这个格式,这个类只处理不同json格式和含有数组的数据类型的转换。代码如下,
public class Json extends TreeMap<String, Object> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	

	public void add(String key, Object value) {
		if (value instanceof String) {
			value = JsonUtil.encode((String) value);
		}
		this.put(JsonUtil.encode(key), value);
	}

	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		boolean first = true;
		for (Iterator<Map.Entry<String, Object>> it = this.entrySet().iterator(); it.hasNext();) {
			Map.Entry<String, Object> me = it.next();
			Object temp = me.getValue();
			if (!first)
				sb.append(",");
			else
				first = false;
			sb.append("'" + me.getKey() + "':");
			if (temp instanceof String || temp.getClass().isPrimitive()
					|| temp.getClass().getName().startsWith("java.lang")) {
				sb.append("'" + temp + "'");
			} else if (temp instanceof Json) {
				sb.append(((Json) temp).toString());
			} else {
				sb.append(temp.toString());
			}
		}
		sb.append("}");
		return sb.toString();
	}

	public String getStringValue(String key) {
		return (String) this.get(key);
	}

	public int getIntValue(String key) {
		String str = getStringValue(key);
		if (str != null)
			str = str.trim();
		return new Integer(str).intValue();
	}

	public String firstKeyString() {
		if (this == null || this.size() == 0)
			throw new RuntimeException("The json map doesn't have any contents!");
		return (String) this.keySet().iterator().next();
	}

	public Date getSqlDate(String key) {
		String dateStr = getStringValue(key);
		try {
			return java.sql.Date.valueOf(dateStr);
		} catch (IllegalArgumentException e) {

		}
		return null;
	}
}

另外有一个Util类来处理一些数据转换, 这个类相当于一个Factory, 也可以用你过来从String parse 一个Json Java对象,
public class JsonUtil {
	public static Json parse(String json) {
		Json js = new Json();
		if (json == null || json.trim().length() == 0 || json.trim().length() == 2)
			return js;
		json = json.substring(1, json.length() - 1);
		char[] chars = json.toCharArray();
		for (int i = 0, n = chars.length; i < n;) {
			StringBuffer sbKey = new StringBuffer();
			while (chars[i] != ':' && i < n) {
				if (chars[i] != '\'')
					sbKey.append(chars[i]);
				i++;
			}
			if (chars[i] == ':') {
				StringBuffer sb = new StringBuffer();
				int j = i + 1;
				if (j < n && chars[j] == '{') {
					int count = 0;
					// j++;
					while (j < n && (chars[j] != '}' || count > 1)) {
						if (chars[j] == '{')
							count++;
						if (chars[j] == '}')
							count--;
						sb.append(chars[j]);
						j++;
					}
					if (j == n)
						return new Json();
					sb.append(chars[j]);
					js.add(sbKey.toString(), parse(sb.toString()));
					i = j + 1;
					while (i < n && chars[i] == ',')
						i++;
				} else if (j < n && chars[j] == '[') {
					int count = 0;
					while (j < n && (chars[j] != ']' || count > 1)) {
						if (chars[j] == '[')
							count++;
						if (chars[j] == ']')
							count--;
						sb.append(chars[j]);
						j++;
					}
					if (j == n)
						return new Json();
					sb.append(chars[j]);
					js.add(sbKey.toString(), buildList(sb.toString()));
					i = j + 1;
					while (i < n && chars[i] == ',')
						i++;
				} else if (j < n) {
					while (j < n) {
						if (chars[j] != '\'')
							sb.append(chars[j]);
						if (j < n - 1 && chars[j + 1] == ',') {
							js.add(sbKey.toString(), sb.toString());
							i = j + 2;
							break;
						} else if (j == n - 1) {
							js.add(sbKey.toString(), sb.toString());
							i = j + 1;
							break;
						}
						j++;
					}
				} else {
					js.add(sbKey.toString(), "");
					i = n;
				}
			}
		}
		return js;
	}
	
	public static List<String> buildList(String value) {
		List<String> result = new ArrayList<String>();
		if (value == null || value.trim().length() <= 2)
			return result;
		value = value.substring(1, value.length() - 1);
		String[] members = value.split(",");
		for (int i = 0, n = members.length; i < n; i++) {
			String temp = members[i];
			if (temp.startsWith("'"))
				result.add(encode(temp.substring(1, temp.length() - 1)));
			else
				result.add(encode(temp));
		}
		return result;
	}
	
	public static String encode(String value) {
		if (value == null)
			return "";
		char content[] = new char[value.length()];
		value.getChars(0, value.length(), content, 0);
		StringBuffer result = new StringBuffer(content.length + 50);
		for (int i = 0; i < content.length; i++) {
			switch (content[i]) {
			case '\'':
				result.append("\\x27");
				break;
			case '\n':
				result.append("\\x0A");
				break;
			case '\r':
				result.append("\\x0D");
				break;
			default:
				result.append(content[i]);
			}
		}
		return result.toString();
	}
	
	public static void main(String[] args) {
		String js = "{'1':'ha','2':'ch','3':['lis't1','lis\nt2','lis\n\rt3']}";
		Json json = JsonUtil.parse(js);
		System.out.println(json);
	}


这里处理了会对前台js识别Json数组有影响的字符, 包括['|\n|\r],这三个。 处理方法是用这些字符的ASCII码来代替,这样js不会把它当作特殊的字符处理比如回车符,而只有在这些字符显示出来的时候才会产生作用。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics