package com.sbell.test;java
import java.lang.reflect.Field;sql
import java.text.DateFormat;json
import java.text.SimpleDateFormat;數組
import java.util.ArrayList;app
import java.util.Date;測試
import java.util.HashMap;ui
import java.util.List;this
import java.util.Map;spa
import java.util.Set;調試
import java.util.Map.Entry;
import javax.persistence.Column;
import javax.persistence.Table;
import com.sbell.entity.User;
/**
* @author wcb
*
*/
public class JsonUtil {
/**
* json = {"json名":[{"key":"value","key2":"value2"},{"key":"value3","key2":"value4"}]}
* @param name
* 本身給json取名
* @param strList
* @param objects
* 防止未來本身要加東西,因此留一個可能加參數的參
* @return 最終format後的json
* @throws Exception
*/
public static String getFormatJson(String name, List strList, Object... objects)
throws Exception {
StringBuffer sb = new StringBuffer();
String json = "{\"%s\":";
sb.append(String.format(json, name));// 格式化json
if (strList == null) {
return json + "}";
}
int fieldsNum = strList.size();// 獲得對象的個數
if (fieldsNum == 0) {
return json + "}";
}
sb.append(getArrayJson(strList) + "}");// 最後記得用 ]} 框起來
return sb.toString();
}
/**
* 把Map轉換成json這裏只考慮 String爲key,list爲value
*
* @param map
* @return String people =
* {
* "programmers": [ { "firstName": "Brett",
* "lastName":"McLaughlin", "email": "aaaa" }, { "firstName":
* "Jason", "lastName":"Hunter", "email": "bbbb" } ],
*
* "authors": [ { "firstName": "Isaac", "lastName": "Asimov",
* "genre": "science fiction" }, { "firstName": "Tad", "lastName":
* "Williams", "genre": "fantasy" } ],
*
* "musicians": [ { "firstName":
* "Eric", "lastName": "Clapton", "instrument": "guitar" }, {
* "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument":"piano" } ]
* }
* @throws Exception
*/
public static String getMapJson(Map<String, List> map) throws Exception {
StringBuffer sb = new StringBuffer();
sb.append("{");
Set<Entry<String, List>> set = map.entrySet();
for (Entry<String, List> e : set) {
String temp = getFormatJson(e.getKey(), e.getValue());
sb.append(temp.substring(1, temp.length() - 1) + ",");// 去掉對象數組格式的json相加最後的
// ,
}
String sub = sb.toString();
sub = sub.substring(0, sub.length() - 1) + "}";// 去掉最後面的 , 並 }
return sub;
}
/**
* 這裏特別說明一下!!調用該方法在只返回鍵值對的時候,最後的json必定要加上 [ ]
* [{"key":"value","key2":"value2"},{"key":"value3","key2":"value4"} ]
* 沒命名的json 也就是json的另外一種表現形式
*
* @param strList
* 通過修改,如今sb.append了[]因此格式已經ok了不是下面這種了而是上面那種
* @return {"key":"value","key2":"value2"},{"key":"value3","key2":"value4"}
* @throws Exception
*/
public static String getArrayJson(List strList) throws Exception {
// String sb = "";
StringBuffer sb = new StringBuffer();
sb.append("[");
int fieldsNum = strList.size();// 獲得對象的個數
if (fieldsNum == 0) {
return "";
}
for (int i = 0; i < fieldsNum; i++) {
// 獲得以{"":"","":""}爲格式的對象 的字符串 對象與對象之間以 , 隔開
// sb+= this.getObject(strList.get(i))+",";
sb.append(getObject(strList.get(i)) + ",");
}
String result = sb.toString();
// 去掉最後一個 ,
result = result.substring(0, result.length() - 1);
result = result + "]";
return result;
}
/**
* 傳入一個Class對象返回
*
* @param obj
* @return {"key":"value","key2":"value2"}
* @throws Exception
*/
public static String getObject(Object obj) throws Exception {
Class c = obj.getClass();
// 獲得表名
String tableName = null;
tableName = c.getSimpleName();
System.out.println(tableName);
// 獲得字段名和字段值 這兩個方便調試
String fieldName = "";
String fieldValue = "";
// 主要看這兩個變量
String json2 = "";
String jsonFormat = "{";
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
/*
* 並非將方法的訪問權限改爲了public, 而是取消java的權限控制檢查。因此即便是public方法, 其accessible
* 屬相默認也是false
*/
field.setAccessible(true);// 若無此句將拋異常
fieldName += field.getName() + ",";
json2 = "\"" + field.getName() + "\":\"%s\",";// "屬性名":"值","":"" 記住
// , 是 分割key value的
// 獲得字段值
Object v = field.get(obj);
/*
* 判斷類型 並格式化 而後拼接到jsonFormat中
*/
if (field.getType() == String.class) {
fieldValue += "'" + v + "'" + ",";
json2 = String.format(json2, v);
jsonFormat += json2;
} else if (field.getType() == Date.class) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = (Date) v;
fieldValue += "'" + df.format(date) + "',";
json2 = String.format(json2, df.format(date));
jsonFormat += json2;
} else {
fieldValue += v + ",";
json2 = String.format(json2, v);
jsonFormat += json2;
}
}
System.out.println(fieldName);
System.out.println(fieldValue);
// 別忘了去掉最後一個 ,
jsonFormat = jsonFormat.substring(0, jsonFormat.length() - 1);
jsonFormat += "}";// 拼接完成! 後面的都是測試調試看的
System.out.println(jsonFormat);
// 去掉最後的逗號
fieldName = fieldName.substring(0, fieldName.length() - 1);
System.out.println(fieldName);
fieldValue = fieldValue.substring(0, fieldValue.length() - 1);
System.out.println(fieldValue);
String sql = "insert into " + tableName + "(" + fieldName + ") values("
+ fieldValue + ")";
System.out.println(sql);
return jsonFormat;
}
public static void main(String[] args) throws Exception {
JsonUtil j = new JsonUtil();
Map<String, List> map = new HashMap<String, List>();
List<User> comList = new ArrayList<User>();
for (int i = 0; i < 5; i++) {
comList.add(new User(i, "acer" + i, "筆記本" + i));
}
for(int i=0;i<3;i++){
map.put(""+i, comList);
}
String temp = j.getFormatJson("User", comList);
System.out.println(temp);
String mapJson = j.getMapJson(map);
System.out.println(mapJson);
//String sub = temp.substring(1,temp.length()-1);
//System.out.println(sub);
}
}