首页 > 代码库 > 为实体类增加toJSON方法
为实体类增加toJSON方法
后期子类继承该基础类即可。
public class BaseEntity implements Serializable { /** * */ private static final long serialVersionUID = -5311594725961174392L; @Override public String toString() { try { return toJSON(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } public String toJSON() throws IllegalArgumentException, IllegalAccessException { StringBuilder jsonBuff = new StringBuilder(); jsonBuff.append("{"); Field[] fields = this.getClass().getDeclaredFields(); for (Field item : fields) { item.setAccessible(true); String name = item.getName(); jsonBuff.append("\"" + name + "\"" + ":"); Object value = item.get(this); if (value != null) { Class<?> type = item.getType(); if (type.equals(String.class)) { jsonBuff.append("\"" + value + "\""); } else if (type.equals(int.class) || type.equals(Integer.class)) { jsonBuff.append(item.getInt(this)); } else if (type.equals(short.class) || type.equals(Short.class)) { jsonBuff.append(item.getShort(this)); } else if (type.equals(long.class) || type.equals(Long.class)) { jsonBuff.append(item.getLong(this)); } else if (type.equals(float.class) || type.equals(Float.class)) { jsonBuff.append(item.getFloat(this)); } else if (type.equals(double.class) || type.equals(Double.class)) { jsonBuff.append(item.getDouble(this)); } else if (type.equals(char.class)) { jsonBuff.append(item.getChar(this)); } else if (type.equals(boolean.class)) { jsonBuff.append(item.getBoolean(this)); } else if (type.equals(Map.class)) { jsonBuff.append(mapToString((Map)value)); } else if (type.equals(List.class)) { jsonBuff.append(listToString((List)value)); } else if (type.getSuperclass().equals(BaseEntity.class)) { jsonBuff.append(((BaseEntity)value).toJSON()); } } jsonBuff.append(", "); } return jsonBuff.substring(0, jsonBuff.length() - 2) + "}"; } public String mapToString(Map<String, ? extends Object> map) { StringBuilder buff = new StringBuilder(); Iterator<String> iter = map.keySet().iterator(); buff.append("{"); while (iter.hasNext()) { String name = iter.next(); Object value = map.get(name); buff.append("\"" + name + "\"" + ":"); if (value != null) { String valueStr = String.valueOf(value); if (value.getClass().equals(String.class)) { buff.append("\"" + valueStr + "\""); } else { buff.append(valueStr); } } buff.append(", "); } return buff.substring(0, buff.length() - 2) + "}"; } public String listToString(List<? extends Object> list) { StringBuilder buff = new StringBuilder(); buff.append("["); for (Object value : list) { String valueStr = String.valueOf(value); if (value.getClass().equals(String.class)) { buff.append("\"" + valueStr + "\""); } else { buff.append(valueStr); } buff.append(", "); } return buff.substring(0, buff.length() - 2) + "]"; } }
为实体类增加toJSON方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。