com.zhenzi.sms.JsonUtil Maven / Gradle / Ivy
package com.zhenzi.sms;
public class JsonUtil {
/**
* 数组转json字符串
*/
public static String toJSONString(String[] array){
if(array == null)
return "[]";
StringBuffer sb = new StringBuffer();
sb.append("[");
for(String item : array){
String val = string(item);
sb.append("\"");
sb.append(val);
sb.append("\"");
sb.append(",");
}
if(sb.length() > 1)
sb.delete(sb.length()-1, sb.length());
sb.append("]");
return sb.toString();
}
/**
* JSON字符串特殊字符处理,比如:“\A1;1300”
*
* @param s
* @return String
*/
private static String string(String s) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '\"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '/':
sb.append("\\/");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
}