java封装对象转json字符串
/**
* Copyright (c) 2011-2015, James Zhan 詹波 (jfinal@126.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package com.jfinal.kit; import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record; /**
* Convert object to json string.
*
* Json java
* string java.lang.String
* number java.lang.Number
* true|false java.lang.Boolean
* null null
* array java.util.List
* object java.util.Map
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class JsonKit { private static int convertDepth = 8;
private static String timestampPattern = "yyyy-MM-dd HH:mm:ss";
private static String datePattern = "yyyy-MM-dd"; public static void setConvertDepth(int convertDepth) {
if (convertDepth < 2)
throw new IllegalArgumentException("convert depth can not less than 2.");
JsonKit.convertDepth = convertDepth;
} public static void setTimestampPattern(String timestampPattern) {
if (timestampPattern == null || "".equals(timestampPattern.trim()))
throw new IllegalArgumentException("timestampPattern can not be blank.");
JsonKit.timestampPattern = timestampPattern;
} public static void setDatePattern(String datePattern) {
if (datePattern == null || "".equals(datePattern.trim()))
throw new IllegalArgumentException("datePattern can not be blank.");
JsonKit.datePattern = datePattern;
} private static String mapToJson(Map map, int depth) {
if(map == null)
return "null"; StringBuilder sb = new StringBuilder();
boolean first = true;
Iterator iter = map.entrySet().iterator(); sb.append('{');
while(iter.hasNext()){
if(first)
first = false;
else
sb.append(','); Map.Entry entry = (Map.Entry)iter.next();
toKeyValue(String.valueOf(entry.getKey()),entry.getValue(), sb, depth);
}
sb.append('}');
return sb.toString();
} private static String toKeyValue(String key, Object value, StringBuilder sb, int depth){
sb.append('\"');
if(key == null)
sb.append("null");
else
escape(key, sb);
sb.append('\"').append(':'); sb.append(toJson(value, depth)); return sb.toString();
} private static String listToJson(List list, int depth) {
if(list == null)
return "null"; boolean first = true;
StringBuilder sb = new StringBuilder();
Iterator iter = list.iterator(); sb.append('[');
while(iter.hasNext()){
if(first)
first = false;
else
sb.append(','); Object value = iter.next();
if(value == null){
sb.append("null");
continue;
}
sb.append(toJson(value, depth));
}
sb.append(']');
return sb.toString();
} /**
* Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
*/
private static String escape(String s) {
if(s == null)
return null;
StringBuilder sb = new StringBuilder();
escape(s, sb);
return sb.toString();
} private static void escape(String s, StringBuilder sb) {
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
switch(ch){
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '/':
sb.append("\\/");
break;
default:
if((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F') || (ch >= '\u2000' && ch <= '\u20FF')) {
String str = Integer.toHexString(ch);
sb.append("\\u");
for(int k=0; k<4-str.length(); k++) {
sb.append('0');
}
sb.append(str.toUpperCase());
}
else{
sb.append(ch);
}
}
}
} public static String toJson(Object value) {
return toJson(value, convertDepth);
} public static String toJson(Object value, int depth) {
if(value == null || (depth--) < 0)
return "null"; if(value instanceof String)
return "\"" + escape((String)value) + "\""; if(value instanceof Double){
if(((Double)value).isInfinite() || ((Double)value).isNaN())
return "null";
else
return value.toString();
} if(value instanceof Float){
if(((Float)value).isInfinite() || ((Float)value).isNaN())
return "null";
else
return value.toString();
} if(value instanceof Number)
return value.toString(); if(value instanceof Boolean)
return value.toString(); if (value instanceof java.util.Date) {
if (value instanceof java.sql.Timestamp)
return "\"" + new SimpleDateFormat(timestampPattern).format(value) + "\"";
if (value instanceof java.sql.Time)
return "\"" + value.toString() + "\"";
return "\"" + new SimpleDateFormat(datePattern).format(value) + "\"";
} if(value instanceof Map) {
return mapToJson((Map)value, depth);
} if(value instanceof List) {
return listToJson((List)value, depth);
} String result = otherToJson(value, depth);
if (result != null)
return result; // 类型无法处理时当作字符串处理,否则ajax调用返回时js无法解析
// return value.toString();
return "\"" + escape(value.toString()) + "\"";
} private static String otherToJson(Object value, int depth) {
if (value instanceof Character) {
return "\"" + escape(value.toString()) + "\"";
} if (value instanceof Model) {
Map map = com.jfinal.plugin.activerecord.CPI.getAttrs((Model)value);
return mapToJson(map, depth);
}
if (value instanceof Record) {
Map map = ((Record)value).getColumns();
return mapToJson(map, depth);
}
if (value instanceof Object[]) {
Object[] arr = (Object[])value;
List list = new ArrayList(arr.length);
for (int i=0; i<arr.length; i++)
list.add(arr[i]);
return listToJson(list, depth);
}
if (value instanceof Enum) {
return "\"" + ((Enum)value).toString() + "\"";
} return beanToJson(value, depth);
} private static String beanToJson(Object model, int depth) {
Map map = new HashMap();
Method[] methods = model.getClass().getMethods();
for (Method m : methods) {
String methodName = m.getName();
int indexOfGet = methodName.indexOf("get");
if (indexOfGet == 0 && methodName.length() > 3) { // Only getter
String attrName = methodName.substring(3);
if (!attrName.equals("Class")) { // Ignore Object.getClass()
Class<?>[] types = m.getParameterTypes();
if (types.length == 0) {
try {
Object value = m.invoke(model);
map.put(StrKit.firstCharToLowerCase(attrName), value);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
}
else {
int indexOfIs = methodName.indexOf("is");
if (indexOfIs == 0 && methodName.length() > 2) {
String attrName = methodName.substring(2);
Class<?>[] types = m.getParameterTypes();
if (types.length == 0) {
try {
Object value = m.invoke(model);
map.put(StrKit.firstCharToLowerCase(attrName), value);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
}
}
return mapToJson(map, depth);
} /**
* TODO
public static Map jsonToMap(String jsonStr) {
throw new RuntimeException("not finished");
}
*/
}
java封装对象转json字符串的更多相关文章
- <摘录>Gson对Java嵌套对象和JSON字符串之间的转换
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,具有良好的跨平台特性.近几年来已经和XML一样成为C/S架构中广泛采用的数据格式.有关JSON的更多知识, ...
- java普通对象和json字符串的互转
一.java普通对象和json字符串的互转 java对象---->json 首先创建一个java对象: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1 ...
- JackSon将java对象转换为JSON字符串
JackSon可以将java对象转换为JSON字符串,步骤如下: 1.导入JackSon 的jar包 2.创建ObjectMapper对象 3.使用ObjectMapper对象的writeValueA ...
- java对象与Json字符串之间的转化(fastjson)
1. 首先引入jar包 在pom.xml文件里加入下面依赖: <dependency> <groupId>com.alibaba</groupId> <art ...
- Json对象与Json字符串的转化、JSON字符串与Java对象的转换
一.Json对象与Json字符串的转化 1.jQuery插件支持的转换方式: $.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以将json字符 ...
- (后端)JackSon将java对象转换为JSON字符串(转)
转载小金金金丶园友: JackSon可以将java对象转换为JSON字符串,步骤如下: 1.导入JackSon 的jar包 2.创建ObjectMapper对象 3.使用ObjectMapper对象的 ...
- Java基础97 json插件的使用(java对象和json字符串对象之间的转换)
1.需要用到的包 2.实例 实体类 people package com.shore.entity; /** * @author DSHORE/2019-4-19 * */ public class ...
- Json对象与Json字符串的转化、JSON字符串与Java对象的转换(转)
一.Json对象与Json字符串的转化 1.jQuery插件支持的转换方式: $.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以将json字符 ...
- java对象与json字符串的互相转换
java对象与json字符串的互相转换 1.采用 net.sf.json.JSONObject maven依赖包: <dependency> <groupId>net.sf.j ...
随机推荐
- ASP.NET MVC 学习1、新增Controller,了解MVC运行机制
1,turorial ,根据链接教程新建一个MVC项目 http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/ ...
- UVa 11732 (Tire树) "strcmp()" Anyone?
这道题也是卡了挺久的. 给出一个字符串比较的算法,有n个字符串两两比较一次,问一共会有多少次比较. 因为节点会很多,所以Tire树采用了左儿子右兄弟的表示法来节省空间. 假设两个不相等的字符串的最长公 ...
- UVa 557 (概率 递推) Burger
题意: 有两种汉堡给2n个孩子吃,每个孩子在吃之前要抛硬币决定吃哪一种汉堡.如果只剩一种汉堡,就不用抛硬币了. 求最后两个孩子吃到同一种汉堡的概率. 分析: 可以从反面思考,求最后两个孩子吃到不同汉堡 ...
- EF4.0和EF5.0增删改查的写法区别及执行Sql的方法
EF4.0和EF5.0增删改查的写法区别 public T AddEntity(T entity) { //EF4.0的写法 添加实体 //db.CreateObjectSet<T>(). ...
- 【转】 Java 多线程之一
转自 Java 多线程 并发编程 一.多线程 1.操作系统有两个容易混淆的概念,进程和线程. 进程:一个计算机程序的运行实例,包含了需要执行的指令:有自己的独立地址空间,包含程序内容和数据:不同进 ...
- POJ 3469 Dual Core CPU (最小割建模)
题意 现在有n个任务,两个机器A和B,每个任务要么在A上完成,要么在B上完成,而且知道每个任务在A和B机器上完成所需要的费用.然后再给m行,每行 a,b,w三个数字.表示如果a任务和b任务不在同一个机 ...
- 【jQuery】鼠标接触按钮后改变图片
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"% ...
- JS调试必备的5个debug技巧
我一直使用printf调试程序,一般来说都是比较顺利,但有时候,你会发现需要更好的方法.下面几个JavaScript技巧相信你一定会觉得十分有用 1. debugger; 我以前也说过,你可以在J ...
- delphi ole word
源代码如下: //Word打印(声明部分) wDoc,wApp:Variant; function PrnWordBegin(tempDoc,docName:String):boolean; func ...
- cocos2d anchor point 锚点解析
anchor point 究竟是怎么回事? 之所以造成不容易理解的是因为我们平时看待一个图片是 以图片的中心点 这一个维度来决定图片的位置的.而在cocos2d中决定一个 图片的位置是由两个维度 一个 ...