`
peirubing
  • 浏览: 32036 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

JsonUtils

 
阅读更多

public class JsonUtils
{
    /**
     * Simple JsonString to obj.
     *
     * @param jsonString
     * @param c
     * @return
     */
    public static Object simpleJsonToObject(String jsonString, Class<?> c)
    {
        try
        {
            JSONObject obj = new JSONObject(jsonString);
            return toObject(obj, c);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * JsonString to obj.
     *
     * @param jsonString
     * @param c
     * @return instance of c and values in string.
     */
    public static Object toObject(String jsonString, Class<?> c)
    {
        try
        {
            JSONObject obj = new JSONObject(jsonString);
            return toObject(obj.getJSONObject(c.getSimpleName()), c);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;

        }

    }

    /**
     *
     * the topName maybe not same with the class c's simple name.
     *
     * @param jsonString
     * @param c
     *            假如是数组就传Example[].class 否则传Example.class 返回的Object是 c的实例
     * @param topName
     *            最外层的key.
     * @return c's new instance.
     */
    public static Object toObject(String jsonString, Class<?> c, String topName)
    {
        try
        {
            if (null == jsonString || jsonString.length() == 0)
            {
                return null;
            }
            JSONObject obj = new JSONObject(jsonString);
            if (c.isArray())
            {
                // array's class name -> [L*******;
                return toObjectArray(obj.optJSONArray(topName), Class.forName(c
                        .getName().substring(2, c.getName().length() - 1)));
            }
            else
            {
                return toObject(obj.optJSONObject(topName), c);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;

        }
    }

    /**
     *
     * obj to JsonString.
     *
     * @param obj
     * @return the jsonString of this obj.
     */
    public static String toJsonString(Object obj)
    {
        return toJsonString(obj, obj.getClass().getSimpleName());
    }

    /**
     *
     * obj to JsonString.
     *
     * @param obj
     * @return the jsonString of this obj.
     */
    public static String toJsonString(Object obj, String topString)
    {
        JSONObject jobj = new JSONObject();
        try
        {
            jobj.putOpt(topString, toJson(obj));
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
        return jobj.toString();
    }

    private static Object[] toObjectArray(JSONArray array, Class<?> c)
    {
        try
        {
            if (array != null && array.length() > 0)
            {
                Object[] objArray = (Object[]) Array.newInstance(c, array
                        .length());
                for (int i = 0; i < array.length(); i++)
                {
                    if ((array.get(i) instanceof String)
                            || (array.get(i) instanceof Long)
                            || (array.get(i) instanceof Double)
                            || (array.get(i) instanceof Boolean))
                    {

                        objArray[i] = array.get(i);
                    }
                    else
                    {
                        if (objArray == null)
                        {
                            objArray = new Object[array.length()];
                        }
                        Object innerObj = toObject(array.getJSONObject(i), c);

                        if (innerObj != null)
                        {
                            objArray[i] = innerObj;
                        }
                    }
                }
                return objArray;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    public static Object toObject(JSONObject jobj, Class<?> c)
    {
        if (c == null || jobj == null)
        {
            return null;
        }
        try
        {
            Object obj = c.newInstance();
            Field[] fields = c.getFields();
            for (Field f : fields)
            {
                String className = f.getType().getName();
                if (className.equals("int")
                        || className.equals(Integer.class.getName()))
                {
                    f.setInt(obj, jobj.optInt(f.getName()));
                }
                else if (className.equals("long")
                        || className.equals(Long.class.getName()))
                {
                    f.setLong(obj, jobj.optLong(f.getName()));
                }
                else if (className.equals("double")
                        || className.equals(Double.class.getName()))
                {
                    f.setDouble(obj, jobj.optDouble(f.getName()));
                }
                else if (className.equals("boolean")
                        || className.equals(Boolean.class.getName()))
                {
                    f.setBoolean(obj, jobj.optBoolean(f.getName()));
                }
                else if (className.equals(String.class.getName()))
                {
                    String s = jobj.optString(f.getName());
                    if (!TextUtils.isEmpty(s))
                    {
                        f.set(obj, s);
                    }
                }
                else if (className.startsWith("[L"))// boolean isArray.
                {
                    JSONArray array = jobj.optJSONArray(f.getName());
                    if (array != null && array.length() > 0)
                    {
                        Class<?> innerClass = Class.forName(className
                                .substring(2, className.length() - 1));
                        Object[] objArray = (Object[]) Array.newInstance(
                                innerClass, array.length());
                        for (int i = 0; i < array.length(); i++)
                        {
                            if ((array.get(i) instanceof String)
                                    || (array.get(i) instanceof Long)
                                    || (array.get(i) instanceof Double)
                                    || (array.get(i) instanceof Boolean))
                            {

                                objArray[i] = array.get(i);
                            }
                            else
                            {
                                if (objArray == null)
                                {
                                    objArray = new Object[array.length()];
                                }
                                Object innerObj = toObject(array
                                        .getJSONObject(i), innerClass);

                                if (innerObj != null)
                                {
                                    objArray[i] = innerObj;
                                }
                            }
                        }
                        f.set(obj, objArray);
                    }
                }
                else
                {
                    JSONObject json = jobj.optJSONObject(f.getName());
                    if (json != null)
                    {
                        Object innerObj = toObject(json, Class.forName(f
                                .getType().getName()));
                        if (innerObj != null)
                        {
                            f.set(obj, innerObj);
                        }
                    }

                }
            }
            return obj;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * obj to JsonObj.
     *
     * @param obj
     *            input obj.
     * @return if obj is array return JsonArray else JsonObject.
     */
    public static Object toJson(Object obj)
    {
        if (obj == null)
        {
            return null;
        }
        try
        {
            if (obj.getClass().isArray())
            {
                JSONArray jArray = null;
                if (((Object[]) obj).length > 0)
                {
                    jArray = new JSONArray();
                    for (int i = 0; i < ((Object[]) obj).length; i++)
                    {
                        if (((Object[]) obj)[i] != null)
                        {
                            Class<?> c = obj.getClass();
                            if (c == int[].class || c == Integer[].class)
                            {
                                jArray.put(((Integer[]) obj)[i]);
                            }
                            else if (c == long[].class || c == Long[].class)
                            {
                                jArray.put(((Long[]) obj)[i]);
                            }
                            else if (c == boolean[].class
                                    || c == Boolean[].class)
                            {
                                jArray.put(((Boolean[]) obj)[i]);
                            }
                            else if (c == double[].class || c == Double[].class)
                            {
                                jArray.put(((Double[]) obj)[i]);
                            }
                            else if (c == String[].class)
                            {
                                jArray.put(((String[]) obj)[i]);
                            }
                            else
                            {
                                jArray.put(toJson(((Object[]) obj)[i]));
                            }
                        }
                    }
                }
                return jArray;
            }
            JSONObject jobj = new JSONObject();
            Field[] f = obj.getClass().getFields();
            for (Field field : f)
            {
                Object inner = field.get(obj);
                if (inner == null)
                {
                    continue;
                }
                Class<?> c = inner.getClass();
                if (c == int.class || c == Integer.class)
                {
                    jobj.putOpt(field.getName(), inner);
                }
                else if (c == long.class || c == Long.class)
                {
                    jobj.putOpt(c.getSimpleName(), inner);
                }
                else if (c == String.class)
                {
                    if (!"".equals(inner))
                    {
                        jobj.putOpt(field.getName(), inner);
                    }
                }
                else
                {
                    jobj.putOpt(field.getName(), toJson(inner));
                }
            }
            return jobj;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
   
    /**
     * InputStream转jsonarray
     * @param is
     * @return
     */
    public static String stream2jarray(InputStream is) {
//        if (is != null) {
//            StringBuffer sb = new StringBuffer();
//            byte[] b = new byte[4096];
//            try {
//                for(int n;(n=is.read(b))!=-1;){
//                    sb.append(new String(b,0,n));
//                }
//                is.close();
//                if(sb.charAt(0) == '{'){
//                    return "["+sb.toString()+"]";
//                }
//                else{
//                    return sb.toString();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return "";
//    }
        StringBuffer buffer = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String tempStr = null;
        try
        {
            while ((tempStr = br.readLine()) != null)
            {
                buffer.append(tempStr);
            }
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return buffer.toString();
       
    }
}

分享到:
评论

相关推荐

    JsonUtils(Json转换工具类)

    《JsonUtils:强大的Json转换工具类》 在Java开发中,JSON作为一种轻量级的数据交换格式,被广泛用于服务器与客户端之间的数据传输。为了方便开发者处理JSON格式的数据,出现了许多库,如Jackson、Gson、Fastjson等...

    Gson工具类JsonUtils

    JsonUtils是一个基于Gson的工具类,它扩展了Gson的功能,提供了一种更便捷的方式来转换Java对象到JSON字符串,以及从JSON字符串反序列化回Java对象。这个工具类还支持泛型和任意类型的转换,极大地简化了开发过程。 ...

    json-lib JsonUtils 工具类,json-lib 工具类

    `JsonUtils.toJSONArray(Object obj)` 和 `JsonUtils.toJSONObject(Object obj)` 分别用于将Java集合(如List, Set)转换为JSONArray对象,以及将Java对象转换为JSONObject对象。这对于处理JSON数组非常有用。 4. ...

    JsonUtils.zip

    在这个场景中,我们关注的是一个名为"JsonUtils"的自定义工具类,它提供了几个便捷的方法来简化这个过程。 `JsonUtils`工具类主要包含三个方法: 1. `objectToJson`: 这个方法用于将Java对象转换成JSON格式的字符...

    JSONUtils json工具类

    json2bean json2xml json2list json2map

    JsonUtils.rar_java jackson解析

    这个"JsonUtils.rar_java jackson解析"压缩包显然包含了使用Jackson进行JSON操作的相关资源和一个名为`JsonUtils.java`的自定义工具类。在这个压缩包中,我们找到了以下四个Jackson库的核心组件: 1. `jackson-...

    jsonutils json工具类

    json数据处理类 将List对象序列化为JSON文本 将对象序列化为JSON文本 将JSON对象数组序列化为JSON文本 将对象转换为List对象 将对象转换为Collection对象 将对象转换为JSON对象数组 将对象转换为JSON对象 ...

    ExceptionUtil.java IDUtils.java JsonUtils.javaPictureResult.java

    以下是对标题"ExceptionUtil.java IDUtils.java JsonUtils.java PictureResult.java"中涉及的知识点的详细说明: 1. **ExceptionUtil.java**: 这个类很可能包含了各种异常处理的静态方法。在Java编程中,异常处理是...

    IT专家在JAVA中封装JSONUtils工具类及使用 (转).docx

    为了方便地处理JSON数据,开发者通常会封装一个工具类,如本例中的`JSONUtils`。这个工具类包含了一系列静态方法,帮助我们将Java对象与JSON格式之间进行转换。下面是对`JSONUtils`工具类中主要方法的详细解释: 1....

    JsonUtils转化工具

    Json转对象,对象转Json

    JSONUtils工具类

    提供对象和json之间的相互转换,方便使用,希望能为你提供帮助。

    Java工具类CookieUtils、IdWorker、JsonUtils、NumberUtils

    工具类CookieUtils、IdWorker、JsonUtils、NumberUtils Java工具类

    untiy操作json,比unity自带的jsonUtils好用多了

    untiy操作json,比unity自带的jsonUtils好用多了 文章地址 https://blog.csdn.net/weixin_44568736/article/details/124608578

    jsonutils:一组简单的JSON包装器

    JSON实用工具 一组简单的JSON包装器 Maven依赖 添加到您的pom.xml &lt; groupId&gt;me.shib.java.lib &lt; artifactId&gt;jsonutils &lt; version&gt;0.0.2 &lt;/ dependency&gt;

    JsonUtils.java

    快速获取复杂JSON中指定key的值,拒绝多次JSON.parseObject和JSONObject.parseObject,快速定位想要的数据!

    JsonUtils:Json 到 C#、VB.Net、Javascript 和 SQL Server 表

    JsonUtils 是一个工具,主要功能是将 JSON 数据转换为 C#、VB.NET、JavaScript 对象以及 SQL Server 的表格。这个工具对于开发人员来说非常实用,因为它简化了在不同编程语言和数据库之间处理 JSON 格式数据的过程。...

    jsonutils:用于 json 对象和 json 对象数组的各种辅助方法

    jsonutils 用于 json 对象和 json 对象数组的各种辅助方法 这是一个正在进行的工作 convertNameValueArrayToObject 获取一组名称值对并将其转换为对象 convertObjectToNameValuePairs 的作用与 ...

Global site tag (gtag.js) - Google Analytics