Java类型转换成Json字符串的工具类小记

public class JsonUtil {  
	   
	  public static String object2json(Object obj) {  
	    StringBuilder json = new StringBuilder();  
	    if (obj == null) {  
	      json.append("\"\"");  
	    } else if (obj instanceof String ||
	         obj instanceof Integer ||
	         obj instanceof Float  ||
	         obj instanceof Boolean ||
	         obj instanceof Short ||
	         obj instanceof Double || 
	         obj instanceof Long ||
	         obj instanceof BigDecimal ||
	         obj instanceof BigInteger || 
	         obj instanceof Byte) {  
	      json.append("\"").append(string2json(obj.toString())).append("\"");  
	    } else if (obj instanceof Object[]) {  
	      json.append(array2json((Object[]) obj));  
	    } else if (obj instanceof List<?>) {  
	      json.append(list2json((List<?>) obj));  
	    } else if (obj instanceof Map<?,?>) {  
	      json.append(map2json((Map<?, ?>) obj));  
	    } else if (obj instanceof Set<?>) {  
	      json.append(set2json((Set<?>) obj));  
	    } else {  
	      json.append(bean2json(obj));  
	    }  
	    return json.toString();  
	  }  
	 
	   
	  public static String bean2json(Object bean) {  
	    StringBuilder json = new StringBuilder();  
	    json.append("{");  
	    PropertyDescriptor[] props = null;  
	    try {  
	      props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors();  
	    } catch (IntrospectionException e) {}  
	    if (props != null) {  
	      for (int i = 0; i < props.length; i++) {  
	        try {  
	          String name = object2json(props[i].getName());  
	          String value = object2json(props[i].getReadMethod().invoke(bean));  
	          json.append(name);  
	          json.append(":");  
	          json.append(value);  
	          json.append(",");  
	        } catch (Exception e) {}  
	      }  
	      json.setCharAt(json.length() - 1, '}');  
	    } else {  
	      json.append("}");  
	    }  
	    return json.toString();  
	  }  
	 
	   
	  public static String list2json(List<?> list) {  
	    StringBuilder json = new StringBuilder();  
	    json.append("[");  
	    if (list != null && list.size() > 0) {  
	      for (Object obj : list) {  
	        json.append(object2json(obj));  
	        json.append(",");  
	      }  
	      json.setCharAt(json.length() - 1, ']');  
	    } else {  
	      json.append("]");  
	    }  
	    return json.toString();  
	  }  
	 
	   
	  public static String array2json(Object[] array) {  
	    StringBuilder json = new StringBuilder();  
	    json.append("[");  
	    if (array != null && array.length > 0) {  
	      for (Object obj : array) {  
	        json.append(object2json(obj));  
	        json.append(",");  
	      }  
	      json.setCharAt(json.length() - 1, ']');  
	    } else {  
	      json.append("]");  
	    }  
	    return json.toString();  
	  }  
	 
	   
	  public static String map2json(Map<?, ?> map) {  
	    StringBuilder json = new StringBuilder();  
	    json.append("{");  
	    if (map != null && map.size() > 0) {  
	      for (Object key : map.keySet()) {  
	        json.append(object2json(key));  
	        json.append(":");  
	        json.append(object2json(map.get(key)));  
	        json.append(",");  
	      }  
	      json.setCharAt(json.length() - 1, '}');  
	    } else {  
	      json.append("}");  
	    }  
	    return json.toString();  
	  }  
	 
	   
	  public static String set2json(Set<?> set) {  
	    StringBuilder json = new StringBuilder();  
	    json.append("[");  
	    if (set != null && set.size() > 0) {  
	      for (Object obj : set) {  
	        json.append(object2json(obj));  
	        json.append(",");  
	      }  
	      json.setCharAt(json.length() - 1, ']');  
	    } else {  
	      json.append("]");  
	    }  
	    return json.toString();  
	  }  
	 
	   
	  public static String string2json(String s) {  
	    if (s == null)  
	      return "";  
	    StringBuilder sb = new StringBuilder();  
	    for (int i = 0; i < s.length(); i++) {  
	      char ch = s.charAt(i);  
	      switch (ch) {  
	      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;  
	      case '/':  
	        sb.append("\\/");  
	        break;  
	      default:  
	        if (ch >= '\u0000' && ch <= '\u001F') {  
	          String ss = Integer.toHexString(ch);  
	          sb.append("\\u");  
	          for (int k = 0; k < 4 - ss.length(); k++) {  
	            sb.append('0');  
	          }  
	          sb.append(ss.toUpperCase());  
	        } else {  
	          sb.append(ch);  
	        }  
	      }  
	    }  
	    return sb.toString();  
	  }  
	} 


测试类

public class Test {
	public static void main(String[] args) {
		Map<String,HashMap<String,Integer>> map = new HashMap<String,HashMap<String,Integer>>();
		HashMap<String,Integer> subMap = new HashMap<String,Integer>();
		subMap.put("普陀", 0);
		subMap.put("长宁", 0);
		subMap.put("徐汇", 0);
		subMap.put("黄浦", 0);
		map.put("上海市", subMap);
		System.out.println(map);
		
		Map<String,Set<String>> m = new HashMap<String,Set<String>>();
		Set<String> s = subMap.keySet();
		m.put("上海市", s);
		
		String json = JsonUtil.map2json(m);
		System.out.println(json);
	}
}





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值