- 浏览: 83262 次
- 性别:
- 来自: 南京
文章分类
最新评论
-
cl1154781231:
怎么解决?
Node cannot be inserted at the specified point in the hierarchy -
sanshizi:
1927105 写道写文档的能力有待提高啊现在如何
一个下拉菜单效果的实现 -
sanshizi:
jacking124 写道看着不是很明白的加入了说明
一个下拉菜单效果的实现 -
sanshizi:
Chris_bing 写道有Jackson,Gson,json ...
将java类生成json -
Chris_bing:
有Jackson,Gson,json-smart那么多类库,干 ...
将java类生成json
package utils; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author Administrator */ public class JSONUtil { /** * 字段过滤模式 */ public static final int INCLUDE = 0; public static final int REMOVE = 1; private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * * @param <T> * @param o * @param maxLength 如果是String型,字符串的最大截取长度 * @param createSub 如果是集合,那么集合中的子对象是否也生成json字串 * @param Map<String, List<String&rt;&rt; filterMap :对指定的类进行字段的过滤 * @param pattern 字段过滤模式:0(NOT)-只考虑已经列出的字段,1(REMOVE)-去除已经列出的字段 * @return */ public static <T> String toJSON(T o, int maxLength, boolean createSub, Map<String, String> filterMap, int pattern) { if (o == null) { return "null"; } return toJSONx(o, o.getClass(), maxLength, createSub, filterMap, pattern, null); } public static <T> String toJSON(T o) { return JSONUtil.toJSON(o, 0, false, null, 0); } public static <T> String toJSON(T o, int maxLength) { return JSONUtil.toJSON(o, maxLength, false, null, 0); } /** * * @param <T> * @param o 要转为json的对象 * @param clazz o的类型,关键时刻,用于强制转换o的类型T为V * @param maxLength * @param createSub * @param filterMap * @param pattern * @param olist 存储已经处理过的对象,在list中的索引越高,层级越深 * @return */ private static <T> String toJSONx(T o, Class clazz, int maxLength, boolean createSub, Map<String, String> filterMap, int pattern, List<Object> olist) { String s = ""; String c = ""; try { if (o != null) { /** * 不知道是何种类型的,利用反射得到元素,但是防止循环引用,此处做一次检查, * 有个缺陷,如果元素对相同对象引用两次,则只会自动转为不考虑下级对象模式,防止死循环 */ olist = olist == null ? (new ArrayList<Object>()) : olist; for (Object vo : olist) { if (vo == o) { createSub = false; S.p("-----(toJSONx)已爬取过,再爬取一次, 但不再考虑下级"); break; } else { olist.add(o); } } c = o.getClass().getName(); //检查各种类型情况 if (String.class.getName().equals(c)) { return S.addDoubleQuot(maxLength > 0 ? S.left(o + "", maxLength) : (o + "")); } else if (o instanceof Number || Boolean.class.getName().equals(c) || boolean.class.getName().equals(c)) { return o + ""; } else if (o instanceof Date) { return S.addDoubleQuot(sdf.format((Date) o)); } else if (o instanceof Collection) { s += "["; int k = 0; for (Object oo : (Collection) o) { if (createSub) { if (k++ > 0) { s += ", "; } s += toJSONx(oo, oo.getClass(), maxLength, createSub, filterMap, pattern, olist); } else { s += getJsonString(oo, maxLength); } } s += "]"; } else if (Map.class.getName().equals(c) || HashMap.class.getName().equals(c)) { s += "{"; int k = 0; Map map = (HashMap) o; for (Object oo : map.keySet()) { if (k++ > 0) { s += ", "; } s += "\"" + S.inDoubleQuot(oo + "") + "\":"; if (map.get(oo) == null) { s += "null"; } else { if (createSub) { s += toJSONx(map.get(oo), oo.getClass(), maxLength, createSub, filterMap, pattern, olist); } else { s += getJsonString(map.get(oo), maxLength); } } } s += "}"; } else if (o != null && o.getClass().isArray()) { s += "["; for (int k = 0; k < Array.getLength(o); k++) { if (createSub) { if (k > 0) { s += ", "; } s += toJSONx(Array.get(o, k), clazz, maxLength, createSub, filterMap, pattern, olist); } else { s += "getJsonString(Array.get(o, k), maxLength)"; } } s += "]"; } else { String[] fieldNames = null; if (filterMap != null && filterMap.get(o.getClass().getName() + "") != null) { fieldNames = S.xstring(filterMap.get(o.getClass().getName() + ""), "").split(","); S.p("----o.getClass():" + o.getClass().getName() + "=" + filterMap.get(o.getClass().getName() + "")); } List<Field> flist = S.getAllFieldsIncludeSuper(clazz); String get = ""; Method method; Object oo = null; if (flist.isEmpty()) { s = "{}"; } else { int k = 0; s += "{"; for (Field f : flist) { c = f.getType().getName(); //字段过滤 if (fieldNames != null) { if (pattern == REMOVE && S.isInArray(f.getName(), fieldNames)) {//去除模式 continue; } else if (pattern == INCLUDE && !S.isInArray(f.getName(), fieldNames)) {//包含模式 continue; } } //看有没有get方法把值给取出来,无法取值的,跳过 get = S.markMethodString(f, "get"); if (S.hasMethod(o.getClass(), get)) { method = o.getClass().getMethod(get); oo = method.invoke(o); } else { continue; } if (k++ > 0) { s += ", "; } s += S.addDoubleQuot(f.getName()) + " : "; //如果抓取下级, 则递归抓取 if (createSub) { s += toJSONx(oo, f.getType(), maxLength, createSub, filterMap, pattern, olist); } else { s += getJsonString(oo, maxLength); } } s += "}"; } } } else { s += null; } } catch (Exception e) { e.printStackTrace(); } return s; } public static String x(int c) { String s = ""; while (c-- > 0) { s += "\t"; } return s; } /** * 生成最大长度为maxLength的字符串,如果maxLength为0,则全部输出 * * @param <T> * @param o * @param maxLength * @return */ public static <T> String getJsonString(T o, int maxLength) { //检查各种类型情况 String s = "", c = ""; if (o == null) { return "null"; } else if (o instanceof Number || Boolean.class.getName().equals((c = o.getClass().getName())) || boolean.class.getName().equals(c)) { s = o + ""; s = maxLength > 0 ? S.left(s, maxLength) : s; } else if (String.class.getName().equals(c)) { s = o + ""; s = S.addDoubleQuot(maxLength > 0 ? S.left(s, maxLength) : s); } else if (o instanceof Date) { s = sdf.format((Date) o); s = S.addDoubleQuot(maxLength > 0 ? S.left(s, maxLength) : s); } else if (o instanceof Collection || (o != null && o.getClass().isArray())) { s = "[]"; } else if (Map.class.getName().equals(c) || HashMap.class.getName().equals(c)) { s = "{}"; } else { s = S.addDoubleQuot(""); } return s; } /** * 一个class是否实现了某个接口 * * @param c * @param szInterface * @return */ public static boolean isInterface(Class c, String szInterface) { Class[] face = c.getInterfaces(); for (int i = 0, j = face.length; i < j; i++) { if (face[i].getName().equals(szInterface)) { return true; } else { Class[] face1 = face[i].getInterfaces(); for (int x = 0; x < face1.length; x++) { if (face1[x].getName().equals(szInterface)) { return true; } else if (isInterface(face1[x], szInterface)) { return true; } } } } if (null != c.getSuperclass()) { return isInterface(c.getSuperclass(), szInterface); } return false; } /** * 得到一个类中所有可用的Field的字符串List * * @param <T> * @param o * @return */ public static <T> List<String> getFieldNameList(T o) { List<String> list = new ArrayList<String>(); try { List<Field> flist = S.getAllFieldsIncludeSuper(((T) o).getClass()); for (Field field : flist) { list.add(field.getName()); } } catch (Exception e) { e.printStackTrace(); } return list; } /** * 向现有的json格式字串添加一个名称为key值为value的 key-value 对 * * @param jsonString * @param key * @param jsonValue , 已经是json格式, 不要再添加引号了 * @return */ public static String push(String jsonString, String key, String jsonValue) { if (S.isEmpty(jsonString) || S.isEmpty(key) || S.isEmpty(jsonValue) || !jsonString.trim().endsWith("}")) { return jsonString; } jsonString = jsonString.trim(); jsonString = jsonString.substring(0, jsonString.length() - 1) + (jsonString.indexOf(":") > 0 ? ", " : "") + S.addDoubleQuot(key) + ": " + jsonValue + "}"; return jsonString; } public static void main(String[] args) { System.out.println(JSONUtil.toJSON(new Date())); } }
S.java
package utils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; public class S { public static DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static DateFormat sdfAli = new SimpleDateFormat("yyyy.MM.dd HH:mm"); public static DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm"); public static DateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd"); public static DecimalFormat df1 = new DecimalFormat("0.0"); public static DecimalFormat df2 = new DecimalFormat("0.00"); public static DecimalFormat df3 = new DecimalFormat("0.000"); public static DecimalFormat df4 = new DecimalFormat("0.0000"); public static DecimalFormat df1x = new DecimalFormat("0.#"); public static DecimalFormat df2x = new DecimalFormat("0.##"); public static DecimalFormat df3x = new DecimalFormat("0.###"); public static DecimalFormat df4x = new DecimalFormat("0.####"); public static final int decode = 1;// 标志是否用 java.net.URLDecoder.decode 解码 public static String xstring(String x) { return (null == x || x.trim().length() == 0) ? null : x.trim(); } public static String xstring(String x, int decode) { return xstring(x, "", decode); } public static String xstring(String x, String defalutValue) { return xstring(x) == null ? defalutValue : xstring(x); } public static String xstring(String x, String defalutValue, int decode) { try { x = java.net.URLDecoder.decode(S.xstring(x, defalutValue), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return x; } public static int xint(String x) { return (int) (xfloat(x)); } public static int xint(String x, int defalutValue) { return xstring(x, "").replaceAll("[^0-9-.]", "").trim().length() == 0 ? defalutValue : xint(x); } public static double xdouble(String x, double defalutValue) { return Double.parseDouble(xstring(xstring(x, "").replaceAll("[^0-9-.]", ""), "0")); } public static double xdouble(String x) { return xdouble(x, 0d); } public static long xlong(String x, long defalutValue) { return xstring(x, "").replaceAll("[^0-9-.]", "").trim().length() == 0 ? defalutValue : ((long) xdouble(x)); } public static long xlong(String x) { return xlong(x, 0l); } public static float xfloat(String x) { return Float.parseFloat(xstring(xstring(x, "").replaceAll("[^0-9-.]", ""), "0")); } public static float xfloat(String x, float defalutValue) { return xstring(x, "").replaceAll("[^0-9-.]", "").trim().length() == 0f ? defalutValue : xfloat(x); } public static String clean(String x) { return S.xstring(x, "").replaceAll("[^0-9a-zA-Z-]", ""); } public static String inSql(String x) { return S.xstring(x, "").replace("'", "''"); } public static String inDoubleQuot(String x) { return S.xstring(x, "").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n"); } public static String addDoubleQuot(String x) { return "\"" + inDoubleQuot(x) + "\""; } public static String inSingleQuot(String x) { return S.xstring(x, "").replace("'", "\\'").replace("\r", "\\r").replace("\n", "\\n"); } public static String addSingleQuot(String x) { return "'" + inSingleQuot(x) + "'"; } public static String riqi(Date date) { if (date == null) { return ""; } return sdf.format(date); } public static String riqi() { return sdf.format(new Date()); } public static String riqiAli(Date date) { return sdfAli.format(date); } public static String riqi2(Date date) { if (date == null) { return ""; } return sdf2.format(date); } public static String riqi2() { return sdf2.format(new Date()); } public static String riqi3(Date date) { if (date == null) { return ""; } return sdf3.format(date); } public static String riqi3() { return sdf3.format(new Date()); } public static String riqi(java.sql.Date date) { return sdf.format(new java.util.Date(date.getTime())); } public static boolean isEmpty(String x) { return x == null || x.trim().equals("") || x.trim().equals("null"); } public static String left(String x, int num) { x = S.xstring(x, ""); return x.length() < num ? x : x.substring(0, num); } public static String right(String x, int num) { x = S.xstring(x, ""); return x.length() <= num ? x : x.substring(x.length() - num); } public static String now() { return sdf.format(System.currentTimeMillis()); } @Deprecated public static boolean isInList(String s, List<String> list) { for (String c : list) { if ((c == null && s == null) || (s != null && s.equals(c))) { return true; } } return false; } @Deprecated public static boolean isInArray(String s, String[] arr) { for (int i = 0; i < arr.length; i++) { if ((arr[i] == null && s == null) || (s != null && s.equals(arr[i]))) { return true; } } return false; } /** * 整数a是否在list中 * * @param a * @param list * @return */ public static boolean inList(int a, List<Integer> list) { for (Integer i : list) { if (a == i.intValue()) { return true; } } return false; } /** * 整数a是否在数组中 * * @param a * @param list * @return */ public static boolean inArray(int a, int[] arr) { for (int i = 0; i < arr.length; i++) { if (a == arr[i]) { return true; } } return false; } public static boolean inArray(String s, String[] arr) { for (int i = 0; i < arr.length; i++) { if ((arr[i] == null && s == null) || (s != null && s.equals(arr[i]))) { return true; } } return false; } @Deprecated public static <T> String toJSON(T o) { return JSONUtil.toJSON(o, 100, false, null, 0); } /** * 将前n个字母大写 * * @param s * @param count * @return */ public static String upper(String s, int n) { if (s == null) { return null; } else if (s.length() <= n) { return s.toUpperCase(); } else { return s.substring(0, n).toUpperCase() + s.substring(n); } } public static String javaUpper(String s) { if (s == null) { return null; } else if (s.length() == 1) { return s.toUpperCase(); } else { if (s.substring(1, 2).replaceAll("[A-Z]", "").length() == 0) { return s; } else { return s.substring(0, 1).toUpperCase() + s.substring(1); } } } /** * 将一个对象中所有String类型decode * * @param <T> * @param o * @param encoding */ public static <T> void decode(T o, String encoding) { if (o != null) { try { Field[] fields = o.getClass().getDeclaredFields(); Method[] methods = o.getClass().getMethods(); String c = ""; String get = ""; String set = ""; int geti = -1; int seti = -1; for (Field f : fields) { c = f.getType().getName(); if (String.class.getName().equals(c)) { geti = -1; seti = -1; for (int idx = 0; idx < methods.length; idx++) { set = S.markMethodString(f, "set"); get = S.markMethodString(f, "get"); if (methods[idx].getName().equals(set)) { seti = idx; } else if (methods[idx].getName().equals(get)) { geti = idx; } if (seti > -1 && geti > -1) { String value = methods[geti].invoke(o) == null ? null : ((String) methods[geti].invoke(o)); if (value != null) { value = java.net.URLDecoder.decode(value, encoding); //value = new String(value.getBytes("iso-8859-1"), "utf-8"); methods[seti].invoke(o, value); } break; } } } } } catch (Exception e) { e.printStackTrace(); } } } public static String markMethodString(Field f, String type) { String s = ""; if ("get".equals(type)) { s = (f.getType().getName().equals(boolean.class.getName()) ? "is" : "get") + javaUpper(f.getName()); } else if ("set".equals(type)) { s = "set" + javaUpper(f.getName()); } return s; } /** * 将一个字符串decode * * @param s * @param encoding * @return */ public static String decode(String s, String encoding) { try { s = s == null ? null : java.net.URLDecoder.decode(s, encoding); } catch (Exception e) { e.printStackTrace(); } return s; } /** * 某个类中是否含有某个set方法 * * @param <T> * @param o * @param field * @return */ public static boolean hasMethod(Class c, String method, Class... parameterTypes) { try { c.getMethod(method, parameterTypes); return true; } catch (Exception e) { //S.p("---S.hasMethod: " + e.toString()); return false; } } /** * 将A转化为B * * @param <A> * @param <B> * @param a * @param b */ public static <A, B> B convert(A a, B b) { try { List<Field> flist = S.getAllFieldsIncludeSuper(b.getClass()); String get = ""; String set = ""; Object o = null; for (Field f : flist) { get = S.markMethodString(f, "get"); set = S.markMethodString(f, "set"); if (S.hasMethod(a.getClass(), get) && S.hasMethod(b.getClass(), set, f.getType())) { o = a.getClass().getMethod(get).invoke(a); b.getClass().getMethod(set, f.getType()).invoke(b, o); } } } catch (Exception e) { S.p("---S.convert(Cast " + a.getClass().getName() + " to " + b.getClass().getName() + "): " + e.toString()); } return b; } public static List<Field> getAllFields(Class c) { List<Field> flist = new ArrayList<Field>(); flist.addAll(Arrays.asList(c.getDeclaredFields())); return flist; } public static List<Field> getAllFieldsIncludeSuper(Class c) { List<Field> flist = new ArrayList<Field>(); flist.addAll(Arrays.asList(c.getDeclaredFields())); flist.addAll(S.getSuperClassFields(c)); return flist; } public static List<Field> getSuperClassFields(Class c) { List<Field> rslist = new ArrayList<Field>(); c = c.getSuperclass(); if (c != null && c.getName() != null && !c.getName().equals(Object.class.getName())) { if (c.getDeclaredFields().length > 0) { rslist.addAll(Arrays.asList(c.getDeclaredFields())); } List<Field> flist = getSuperClassFields(c); rslist.addAll(flist); } return rslist; } public static void p(String s) { System.out.println(s); } public static void p() { System.out.println(""); } public static void main(String[] args) { } }
评论
2 楼
sanshizi
2012-10-25
Chris_bing 写道
有Jackson,Gson,json-smart那么多类库,干嘛要自己写啊
呵呵, 目前还处在学习阶段, 见笑见笑
1 楼
Chris_bing
2012-10-21
有Jackson,Gson,json-smart那么多类库,干嘛要自己写啊
发表评论
-
[转]java图片处理的一些代码
2013-06-13 12:12 1060package com.adam.dev.pic.ea ... -
java 放大镜效果
2013-06-13 10:21 2908坛里看到, 备忘一下 这里用到第三方库, 主要是做高斯模糊用的 ... -
分享一个play framework的DuplicateMemberException冲突
2013-05-17 09:48 3141分享一个play framework的DuplicateMem ... -
nutz创建表报错
2012-06-16 12:48 1878偶用nutz创建表, 报如下错, DataSource 可 ... -
用java读取svn数据, oh yeah
2012-06-12 15:02 1731用java读取svn数据, 请猛击此处 Aut ... -
[转]Java 数字签名(Digital Signature)的批处理文件制作
2012-06-02 15:59 1228出处: http://blog.csdn.net/casula ...
相关推荐
java服务端生成json(json服务端),可以在浏览器上访问获取查看json,已测试通过
1.一款将java对象转成json或是将json转成java对象的jar文件; 2.在网上找了半天才找到,希望大家共享; 3.使用方法,大家在网上随便找,很多,很简单,一看便会; 4.此包在eclipse中和AndroidStudio中都可以用,但是,你如果...
java后台生成JSON数据和EXT互传数据,全靠它实现。
java开发生成json的jar包 java开发生成json的jar包
========使用java代码生成json文件和word文档!=======
对象生成json字符串,根据字符串生成对象|list
java对象生成json字符串实例(eclipse工程),生成的结果如下: {"stuList":[{"stuname":"stu_jack","stuno":"stu001"},{"stuname":"stu_jack2","stuno":"stu002"}],"teaname":"tea_jack","teano":"tea_001"} 自己可以...
java转JSON串的几种方式: 1、将java对象转成json串 2、通过JSONObject生成json串 3、通过json字符串生成json串 代码通过阿里的fastjson包实现。
自己编写的通过java语言生成JSON数据格式。已经用于项目了,目前该项目中没有增加对JSON的解析部分!
外国人用pb9.0开发的pb生成与解析json的例子,有源码,可以直接使用很清晰明了。
Java递归算法构造JSON树形结构,Java递归算法构造JSON树形结构Java递归算法构造JSON树形结构
createJson.rar Java生成各种json格式数据 生成JSON数据:{"name":"zhagnsan","age":24} 生成JSON数据:[{"name":"zhangsan","age":24},{"name":"lisi","age":25},{"name":"wangwu","age":26}] 生成JSON数据:{...
由此,在开源代码有老外使用Java生成JSON代码,本例子是翻写老外的开源例子,在使用部分有非常详细的注释说明,是学习使用Java封装客户端对象的好例子。 环境:Window XP professional, Ant 1.7, JDK 1.6 注意:本...
从Java对象生成JSON的过程称为 [序列化Java对象到JSON] 为什么用它? 答:我数据库中的主键是使用雪花算法生成的,就是因为用id的位数太多,导致在前台我点击删除/修改按钮后传入到后端的id会缺少精度。(比如本应该...
自己写的java json 生成工具,lyz包下面的lyzjson是我自己写的,util包下面的JsonUtil是老师写的。看下谁的好用点。多提建议,谢谢。
json格式转换为java实体类,idea导入即可,功能非常好用。直接允许main函数即可完成
java解析xml文件生成json对象,方便操作,下载后导入eclipse,加入相关的jar包后加载至类路径便可测试该工具类,很好用!!!
PB解析和生成JSON,解析JSON是否成功,生成默认JSON。
将json转换为javebean的工具,封装jsonschema2pojo,用户可以修改配置文件json2Beans.json,然后运行Json2JavaBean2.bat直接生成对应类。 能够批量转换json为bean,直接拷贝到项目中使用。 提醒: 需要提前安装java...
java写json时所要用到的jar包,生成的json格式详情可看我的博客文章