最近在学Json,自己写了个Java to Json的转换器,但有个两情相爱的问题还没有解决。
欢迎砸砖,提建议,提bug~
/**
* java object <-> json string 转换器
*
* @author kevinxu
*
*/
public class JsonConvertor {
/**
* 特殊字符
*
* @param s
* @return
*/
static String string2Json(String s) {
StringBuilder sb = new StringBuilder(s.length());
sb.append('\"');
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);
}
}
sb.append('\"');
return sb.toString();
}
static String number2Json(Number number) {
return number.toString();
}
static String boolean2Json(Boolean bool) {
return bool.toString();
}
static String array2Json(Object[] array) {
if (array.length == 0)
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (Object o : array) {
sb.append(toJson(o));
sb.append(',');
}
sb.setCharAt(sb.length() - 1, ']');
return sb.toString();
}
static String map2Json(Map<String, Object> map) {
if (map.isEmpty())
return "{}";
StringBuilder sb = new StringBuilder();
sb.append('{');
Set<String> keys = map.keySet();
for (String key : keys) {
Object value = map.get(key);
sb.append('\"');
sb.append(key);
sb.append('\"');
sb.append(':');
sb.append(toJson(value));
sb.append(',');
}
sb.setCharAt(sb.length() - 1, '}');
return sb.toString();
}
/**
* 对外的接口
*
* @param o
* @return
* @throws RuntimeException
*/
public static String toJson(Object o) throws RuntimeException {
if (o == null)
return "null";
if (o instanceof String)
return string2Json((String) o);
if (o instanceof Boolean)
return boolean2Json((Boolean) o);
if (o instanceof Number)
return number2Json((Number) o);
if (o instanceof Map)
return map2Json((Map<String, Object>) o);
if (o instanceof List)
return list2Json((List<?>) o);
if (o instanceof Object[])
return array2Json((Object[]) o);
// JavaBean to Json
return beanToJson(o);
}
private static String list2Json(List<?> list) {
if ((null == list) || (list.size() == 0))
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (Object o : list) {
sb.append(toJson(o));
sb.append(',');
}
sb.setCharAt(sb.length() - 1, ']');
return sb.toString();
}
/**
* 用反射方法解析JavaBean
*
* @param o
* @return
*/
private static String beanToJson(Object o) {
Class<?> c = o.getClass();
Method[] methods = c.getDeclaredMethods();
StringBuilder sb = new StringBuilder();
sb.append("{");
for (Method method : methods) {
String methodName = method.getName();
if (methodName.startsWith("get")) {
try {
Object returnValue = method.invoke(o);
String key = methodName.substring("get".length());
sb.append('\"');
sb.append(key);
sb.append('\"');
sb.append(':');
sb.append(toJson(returnValue));
sb.append(',');
} catch (Exception e) {
e.printStackTrace();
}
}
}
sb.setCharAt(sb.length() - 1, '}');
return sb.toString();
}
public static void main(String args[]) {
People pretty = new People();
pretty.setName("灰姑娘");
pretty.setTelphone("110");
List<String> habits = new ArrayList<String>();
habits.add("看电影");
habits.add("八卦");
pretty.setHabtis(habits);
People handSome = new People();
handSome.setName("王子");
handSome.setTelphone("111");
List<String> kingHabits = new ArrayList<String>();
kingHabits.add("敲代码");
kingHabits.add("砍树");
handSome.setHabtis(kingHabits);
pretty.setLover(handSome);
// 注意这段代码,想想写了会有什么效果?
// 从OO来看,告诉人家灰姑娘的爱人是王子,同时也告诉王子的爱人是灰姑娘,不是两情相愿吗?
// 但实际是程序会抛异常StackOverflowError,哈~
// 因为爱了对方,对方给回爱,对方又给回爱,爱无止境,哪不累死?
// 但不设置的话,会看到爱人的爱人是null, 哪位高手来帮忙解决这个问题
// handSome.setLover(pretty);
System.out.println(toJson(pretty));
}
}
class People {
private String name;
private String telphone;
private List<String> habtis;
private People Lover;
public List<String> getHabtis() {
return habtis;
}
public void setHabtis(List<String> habtis) {
this.habtis = habtis;
}
public String getName() {
return name;
}
public People getLover() {
return Lover;
}
public void setLover(People lover) {
Lover = lover;
}
public void setName(String name) {
this.name = name;
}
public String getTelphone() {
return telphone;
}
public void setTelphone(String telphone) {
this.telphone = telphone;
}
}
运行结果:
{"Habtis":["看电影","八卦"],"Lover":{"Habtis":["敲代码","砍树"],"Lover":
null,"Telphone":"111","Name":"王子"},"Telphone":"110","Name":"灰姑娘"}