java封装对象转json字符串

/**
 * Copyright (c) 2011-2015, James Zhan 詹波 ([email protected]).
 *
 * 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");
    }
    */
}
时间: 2024-10-22 05:02:42

java封装对象转json字符串的相关文章

&lt;摘录&gt;Gson对Java嵌套对象和JSON字符串之间的转换

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,具有良好的跨平台特性.近几年来已经和XML一样成为C/S架构中广泛采用的数据格式.有关JSON的更多知识,请参考以下内容:http://json.org/json-zh.html 在服务器和客户端之间使用JSON数据格式进行通信,经常会涉及到JAVA对象和JSON字符串之间的转换.通常,我们可以使用一些JSON解析工具,例如:Gson,FastJson等.当然,我们也可以手动解析,只是会比较繁琐. 下面

Json对象与Json字符串的转化、JSON字符串与Java对象的转换

Json对象与Json字符串的转化.JSON字符串与Java对象的转换 一.Json对象与Json字符串的转化 1.jQuery插件支持的转换方式: $.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以将json字符串转换成json对象 2.浏览器支持的转换方式(Firefox,chrome,opera,safari,ie9,ie8)等浏览器: JSON.stringify(obj)将JSON转为字符串.JSON.parse(string)

JackSon将java对象转换为JSON字符串

JackSon可以将java对象转换为JSON字符串,步骤如下: 1.导入JackSon 的jar包 2.创建ObjectMapper对象 3.使用ObjectMapper对象的writeValueAsString()方法将java对象转换为JSON对象 这里有个例子: public class Fruit { private String name; private String id; public Customet(String name, String id) { super(); th

java对象与Json字符串之间的转化(fastjson)

1. 首先引入jar包 在pom.xml文件里加入下面依赖: <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.51</version> </dependency> 2. 创建一个Person类(方面下面使用) public class Person implements Comp

java对象转为json字符串

1.使用fastjson开源json工具类库 2.java类未添加get()和set()方法,java对象初始化时,使用fastjson解析,得到的json字符串有时为空{} 3.Java对象转为json字符串,初始化时最好添加get()和set()方法,避免错误 原文地址:https://www.cnblogs.com/cty136/p/11521264.html

Json对象和Json字符串的区别

JSON对象 有时候在做项目的时候时常将这两个概念弄混淆,尤其是在使用springmvc的时候,后台@RequestBody接受的是一个json格式的字符串,一定是一个字符串. 先介绍一下json对象,首先说到对象的概念,对象的属性是可以用:对象.属性进行调用的.例如: var person={"name":"zhangsan","sex":"男","age":"24"}//json对象

JSON实用类,用来实现对象和JSON字符串的互相转换

import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Lis

Java类对象和Json数据之间的转换

表字段过多,不想分别保存到数据中,使用频率低,所以考虑使用Jave类 -- Json之间的数据转换. 1.类转换Json,并保存到数据 Attribute.java 1 /** 2 * 属性数据结构 3 * 4 */ 5 public class Attribute { 6 7 private static final long serialVersionUID = -1L; 8 9 private Long attrId; 10 11 private List<AttributeValue>

使用Google的Gson实现对象和json字符串之间的转换

需要gson.jar 1.JsonUtil.java Java代码   package com.snail.json; import java.lang.reflect.Type; import com.google.gson.Gson; /** * Java对象和JSON字符串相互转化工具类 * @author penghuaiyi * @date 2013-08-10 */ public final class JsonUtil { private JsonUtil(){} /** * 对象