JsonUtil-本人原创

package com.sbell.test;

 

import java.lang.reflect.Field;

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

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这里只考虑 Stringkeylistvalue

 * 

 * @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);

}

}


转载于:https://my.oschina.net/u/2436852/blog/493192

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值