一个简单的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不会把它当作特殊的字符处理比如回车符,而只有在这些字符显示出来的时候才会产生作用。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值