Home > Java > javaTutorial > Detailed explanation of sample code for converting Java objects to JSON

Detailed explanation of sample code for converting Java objects to JSON

黄舟
Release: 2017-09-06 09:48:24
Original
1694 people have browsed it

先说下我自己的理解,一般而言,JSON字符串要转为java对象需要自己写一个跟JSON一模一样的实体类bean,然后用bean.class作为参数传给对应的方法,实现转化成功。

上述这种方法太麻烦了。其实有一种东西叫jsonObject可以直接不用新建实体类bean,而实现转化,先说org.json.JSONObject这个JSONObject,贴上代码:

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONObject;

/**
* Json工具类,实现了实体类和Json数据格式之间的互转功能 使用实例:<br>
*/
public class JsonUtils {
    /**
     * 将一个实体类对象转换成Json数据格式
     * 
     * @param bean
     *            需要转换的实体类对象
     * @return 转换后的Json格式字符串
     */
    private static String beanToJson(Object bean) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        PropertyDescriptor[] props = null;
        try {
            props = Introspector.getBeanInfo(bean.getClass(), Object.class)
                    .getPropertyDescriptors();
        } catch (IntrospectionException e) {
        }
        if (props != null) {
            for (int i = 0; i < props.length; i++) {
                try {
                    String name = objToJson(props[i].getName());
                    String value = objToJson(props[i].getReadMethod()
                            .invoke(bean));
                    json.append(name);
                    json.append(":");
                    json.append(value);
                    json.append(",");
                } catch (Exception e) {
                }
            }
            json.setCharAt(json.length() - 1, &#39;}&#39;);
        } else {
            json.append("}");
        }
        return json.toString();
    }


    /**
     * 将一个List对象转换成Json数据格式返回
     * 
     * @param list
     *            需要进行转换的List对象
     * @return 转换后的Json数据格式字符串
     */
    private static String listToJson(List<?> list) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (list != null && list.size() > 0) {
            for (Object obj : list) {
                json.append(objToJson(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, &#39;]&#39;);
        } else {
            json.append("]");
        }
        return json.toString();
    }

    /**
     * 将一个对象数组转换成Json数据格式返回
     * 
     * @param array
     *            需要进行转换的数组对象
     * @return 转换后的Json数据格式字符串
     */
    private static String arrayToJson(Object[] array) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (array != null && array.length > 0) {
            for (Object obj : array) {
                json.append(objToJson(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, &#39;]&#39;);
        } else {
            json.append("]");
        }
        return json.toString();
    }

    /**
     * 将一个Map对象转换成Json数据格式返回
     * 
     * @param map
     *            需要进行转换的Map对象
     * @return 转换后的Json数据格式字符串
     */
    private static String mapToJson(Map<?, ?> map) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        if (map != null && map.size() > 0) {
            for (Object key : map.keySet()) {
                json.append(objToJson(key));
                json.append(":");
                json.append(objToJson(map.get(key)));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, &#39;}&#39;);
        } else {
            json.append("}");
        }
        return json.toString();
    }

    /**
     * 将一个Set对象转换成Json数据格式返回
     * 
     * @param set
     *            需要进行转换的Set对象
     * @return 转换后的Json数据格式字符串
     */
    private static String setToJson(Set<?> set) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (set != null && set.size() > 0) {
            for (Object obj : set) {
                json.append(objToJson(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, &#39;]&#39;);
        } else {
            json.append("]");
        }
        return json.toString();
    }

    private static String stringToJson(String s) {
        if (s == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            switch (ch) {
            case &#39;"&#39;:
                sb.append("\\\"");
                break;
            case &#39;\\&#39;:
                sb.append("\\\\");
                break;
            case &#39;\b&#39;:
                sb.append("\\b");
                break;
            case &#39;\f&#39;:
                sb.append("\\f");
                break;
            case &#39;\n&#39;:
                sb.append("\\n");
                break;
            case &#39;\r&#39;:
                sb.append("\\r");
                break;
            case &#39;\t&#39;:
                sb.append("\\t");
                break;
            case &#39;/&#39;:
                sb.append("\\/");
                break;
            default:
                if (ch >= &#39;\u0000&#39; && ch <= &#39;\u001F&#39;) {
                    String ss = Integer.toHexString(ch);
                    sb.append("\\u");
                    for (int k = 0; k < 4 - ss.length(); k++) {
                        sb.append(&#39;0&#39;);
                    }
                    sb.append(ss.toUpperCase());
                } else {
                    sb.append(ch);
                }
            }
        }
        return sb.toString();
    }

    public static String objToJson(Object obj) {
        StringBuilder json = new StringBuilder();
        if (obj == null) {
            json.append("\"\"");
        } else if (obj instanceof Number) {
            Number num = (Number)obj;
            json.append(num.toString());
        } else if (obj instanceof Boolean) {
            Boolean bl = (Boolean)obj;
            json.append(bl.toString());
        } else if (obj instanceof String) {
            json.append("\"").append(stringToJson(obj.toString())).append("\"");
        } else if (obj instanceof Object[]) {
            json.append(arrayToJson((Object[]) obj));
        } else if (obj instanceof List) {
            json.append(listToJson((List) obj));
        } else if (obj instanceof Map) {
            json.append(mapToJson((Map) obj));
        } else if (obj instanceof Set) {
            json.append(setToJson((Set) obj));
        } else {
            json.append(beanToJson(obj));
        }
        return json.toString();
    }
    
    /**
      * @Title: json2Map
      * @Creater: chencc <br>
      * @Date: 2011-3-28 <br>
      * @Description: TODO转化json2map
      * @param @param jsonString
      * @param @return
      * @return Map<String,Object>
      * @throws
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> json2Map(String jsonString) {
        
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if(null != jsonString && !"".equals(jsonString)){
                JSONObject jsonObject = new JSONObject(jsonString);
            
                Iterator keyIter = jsonObject.keys();
                String key = "";
                Object value = null;
            
                while (keyIter.hasNext()) {
                    key = (String) keyIter.next();
                    value = jsonObject.get(key);
                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
    
    //测试方法
    public static void main(String[] args) {
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("callId123", Integer.valueOf(1000));
        Map retMap = new HashMap();
        retMap.put("params", params);
        retMap.put("result", true);
        List ls = new ArrayList();
        ls.add(new HashMap());
        ls.add("hello world!!");
        ls.add(new String[4]);
        retMap.put("list", ls);
        
        String[] strArray = new String[10];
        strArray[1]="first";
        strArray[2]="2";
        strArray[3]="3";
        System.out.println("Boolean:"+JsonUtils.objToJson(true));
        System.out.println("Number:"+JsonUtils.objToJson(23.3));
        System.out.println("String:"+JsonUtils.objToJson("sdhfsjdgksdlkjfk\"sd,!#%$^&*#(*@&*%&*$fsdfsdfsdf"));
        System.out.println("Map :"+JsonUtils.objToJson(retMap));
        System.out.println("List:"+JsonUtils.objToJson(ls));
        System.out.println("Array:"+JsonUtils.objToJson(strArray));
        
        String json = JsonUtils.objToJson(retMap);
        Map r = JsonUtils.json2Map(json);
        System.out.println(r.get("callId123"));
        
        
    }
}
Copy after login

再来聊聊net.sf.json.JSONObject这个JSONObject,代码如下

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.PropertyFilter;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
    
    
    private static ObjectMapper objectMapper = null;
    /**
     * JSON初始化
     */
    static {
        objectMapper = new ObjectMapper();  
        //设置为中国上海时区  
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));  
        //空值不序列化  
        objectMapper.setSerializationInclusion(Include.NON_NULL);  
        //反序列化时,属性不存在的兼容处理  
        objectMapper.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);  
        //序列化时,日期的统一格式  
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));  

        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);  
        
    } 
    
    
    /**
     * 把对象转换成为Json字符串
     *
     * @param obj
     * @return
     */
    public static String convertObjectToJson(Object obj) {
        if (obj == null) {
//                throw new IllegalArgumentException("对象参数不能为空。");
            return null;
        }
        try {
            return objectMapper.writeValueAsString(obj);

        }  catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
    /**
     *  把json字符串转成Object对象
     * @param jsonString
     * @return T
     */
    public static <T> T parseJsonToObject(String jsonString, Class<T> valueType) {
        
        if(jsonString == null || "".equals((jsonString))){
            return null;
        }
        try {
            return objectMapper.readValue(jsonString, valueType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     *  把json字符串转成List对象
     * @param jsonString
     * @return List<T>
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> parseJsonToList(String jsonString,Class<T> valueType) {
        
        if(jsonString == null || "".equals((jsonString))){
            return null;
        }
        
        List<T> result = new ArrayList<T>();
        try {
            List<LinkedHashMap<Object, Object>> list = objectMapper.readValue(jsonString, List.class);
            
            for (LinkedHashMap<Object, Object> map : list) {
                
                String jsonStr = convertObjectToJson(map);
                
                T t = parseJsonToObject(jsonStr, valueType);
                
                result.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * JSON处理含有嵌套关系对象,避免出现异常:net.sf.json.JSONException: There is a cycle in the hierarchy的方法
     * 注意:这样获得到的字符串中,引起嵌套循环的属性会置为null
     *
     * @param obj
     * @return
     */
    public static JSONObject getJsonObject(Object obj) {

        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
            
            @Override
            public boolean apply(Object source, String name, Object value) {
                if(value==null){
                    return true;
                }
                return false;
            }
        });
        return JSONObject.fromObject(obj, jsonConfig);
    }
    /**
     * JSON处理含有嵌套关系对象,避免出现异常:net.sf.json.JSONException: There is a cycle in the hierarchy的方法

     * 注意:这样获得到的字符串中,引起嵌套循环的属性会置为null
     *
     * @param obj
     * @return
     */
    public static JSONArray getJsonArray(Object obj) {

        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

        return JSONArray.fromObject(obj, jsonConfig);
    }
    /**
     * 解析JSON字符串成一个MAP
     *
     * @param jsonStr json字符串,格式如: {dictTable:"BM_XB",groupValue:"分组值"}
     * @return
     */
    public static Map<String, Object> parseJsonStr(String jsonStr) {

        Map<String, Object> result = new HashMap<String, Object>();

        JSONObject jsonObj = JsonUtil.getJsonObject(jsonStr);

        for (Object key : jsonObj.keySet()) {
            result.put((String) key, jsonObj.get(key));
        }
        return result;
    }

}
Copy after login

总结:net.sf.json.JSONObject这个属于json-lib这个老牌的系列,依赖的包超级多,commons的lang、logging、beanutils、collections等组件都有。

而org.json则相对来说依赖的包少一些,速度和性能方面没有怎么进行测试。

The above is the detailed content of Detailed explanation of sample code for converting Java objects to JSON. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template