写一个toJSON方法将Map对象转换成JSON字符串

写一个toJSON方法将Map 对象转换成JSON字符串

/**
 * 
 * @author gavin
 *
 */
public class Gson{
public static String toJson(Map<String,String> map){
   Set<String> keys = map.keySet();
   String key = "";
   String value = "";
   StringBuffer jsonBuffer = new StringBuffer();
   jsonBuffer.append("{");    
   for(Iterator<String> it = keys.iterator();it.hasNext();){
       key =  (String)it.next();
       value = map.get(key);
       jsonBuffer.append(key+":"+value);
       if(it.hasNext()){
            jsonBuffer.append(",");
       }
   }
   jsonBuffer.append("}");
   return jsonBuffer.toString();
}
public static String toJson2(Map<String,String> map){
Set<Map.Entry<String, String>> entrys = map.entrySet();
Map.Entry<String, String> entry = null;
   String key = "";
   String value = "";
   StringBuffer jsonBuffer = new StringBuffer();
   jsonBuffer.append("{");    
   for(Iterator<Map.Entry<String, String>> it = entrys.iterator();it.hasNext();){
    entry =  (Map.Entry<String, String>)it.next();
    key = entry.getKey();
       value = entry.getValue();
       jsonBuffer.append(key+":"+value);
       if(it.hasNext()){
            jsonBuffer.append(",");
       }
   }
   jsonBuffer.append("}");
   return jsonBuffer.toString();
}
public static void main(String args[]){
Map<String,String> map = new TreeMap<String,String>();
map.put("1", "zhangyi");
map.put("2", "zhanger");
map.put("3", "zhangsan");
map.put("4", "zhangsi");
map.put("5", "zhangwu");
System.out.println(toJson(map));
System.out.println(toJson2(map));
}
}

运行结果:

{1:zhangyi,2:zhanger,3:zhangsan,4:zhangsi,5:zhangwu}
{1:zhangyi,2:zhanger,3:zhangsan,4:zhangsi,5:zhangwu}


Gavin

你可能感兴趣的:(写一个toJSON方法将Map对象转换成JSON字符串)