标签:
1 package com; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 import java.util.Set; 8 9 import org.junit.Test; 10 11 public class TestJson { 12 13 static String string2Json(String s) { 14 StringBuilder sb = new StringBuilder(s.length() + 20); 15 sb.append(‘\"‘); 16 for (int i = 0; i < s.length(); i++) { 17 char c = s.charAt(i); 18 switch (c) { 19 case ‘\"‘: 20 sb.append("\\\""); 21 break; 22 case ‘\\‘: 23 sb.append("\\\\"); 24 break; 25 case ‘/‘: 26 sb.append("\\/"); 27 break; 28 case ‘\b‘: 29 sb.append("\\b"); 30 break; 31 case ‘\f‘: 32 sb.append("\\f"); 33 break; 34 case ‘\n‘: 35 sb.append("\\n"); 36 break; 37 case ‘\r‘: 38 sb.append("\\r"); 39 break; 40 case ‘\t‘: 41 sb.append("\\t"); 42 break; 43 default: 44 sb.append(c); 45 } 46 } 47 sb.append(‘\"‘); 48 return sb.toString(); 49 } 50 51 static String number2Json(Number number) { 52 return number.toString(); 53 } 54 55 static String boolean2Json(Boolean bool) { 56 return bool.toString(); 57 } 58 59 static String array2Json(Object[] array) { 60 if (array.length == 0) 61 return "[]"; 62 StringBuilder sb = new StringBuilder(array.length << 4); 63 sb.append(‘[‘); 64 for (Object o : array) { 65 sb.append(toJson(o)); 66 sb.append(‘,‘); 67 } 68 // 将最后添加的 ‘,‘ 变为 ‘]‘: 69 sb.setCharAt(sb.length() - 1, ‘]‘); 70 return sb.toString(); 71 } 72 73 static String map2Json(Map<String, Object> map) { 74 if (map.isEmpty()) 75 return "{}"; 76 StringBuilder sb = new StringBuilder(map.size() << 4); 77 sb.append(‘{‘); 78 Set<String> keys = map.keySet(); 79 for (String key : keys) { 80 Object value = map.get(key); 81 sb.append(‘\"‘); 82 sb.append(key); 83 sb.append(‘\"‘); 84 sb.append(‘:‘); 85 sb.append(toJson(value)); 86 sb.append(‘,‘); 87 } 88 // 将最后的 ‘,‘ 变为 ‘}‘: 89 sb.setCharAt(sb.length() - 1, ‘}‘); 90 return sb.toString(); 91 } 92 93 public static String toJson(Object o) { 94 if (o == null) 95 return "null"; 96 if (o instanceof String) 97 return string2Json((String) o); 98 if (o instanceof Boolean) 99 return boolean2Json((Boolean) o); 100 if (o instanceof Number) 101 return number2Json((Number) o); 102 if (o instanceof Map) 103 return map2Json((Map<String, Object>) o); 104 if (o instanceof Object[]) 105 return array2Json((Object[]) o); 106 throw new RuntimeException("Unsupported type: " 107 + o.getClass().getName()); 108 } 109 110 @Test(expected = StackOverflowError.class) 111 public void testRecurrsiveMap2Json() { 112 Map<String, Object> map = new HashMap<String, Object>(); 113 map.put("key", "value"); 114 map.put("key2", 2); 115 List<Integer> array = new ArrayList<Integer>(); 116 array.add(1); 117 array.add(2); 118 map.put("array", array); 119 String json = TestJson.toJson(map); 120 System.out.println(json); 121 } 122 }
参考文献:
http://www.ibm.com/developerworks/cn/web/wa-lo-json/
http://www.w3school.com.cn/json/index.asp
标签:
原文地址:http://www.cnblogs.com/gaoyanqing/p/4803614.html