如何将JSON、Map、List三者间灵活转换?
- 内容介绍
- 文章标签
- 相关推荐
本文共计400个文字,预计阅读时间需要2分钟。
java/** * 工作中常用的JSON转换工具集 * * Created with IntelliJ IDEA. * User: yuyue * Date: 14-7-23 * Time: 下午7:51 * /public class JsonHelper { * * map转json,list转map,map转json的工具集合 * * @param object 是一个 对象 */
/**
* Created with IntelliJ IDEA.
* User: yuyue
* Date: 14-7-23
* Time: 下午7:51
*/
public class JsonHelper {
/**
* map转json
*
* @param object 是一个map
* @return
* @throws JSONException
*/
public static Object mapToJSON(Object object) throws JSONException {
if (object instanceof Map) {
JSONObject json = new JSONObject();
Map map = (Map) object;
for (Object key : map.keySet()) {
json.put(key.toString(), mapToJSON(map.get(key)));
}
return json;
} else if (object instanceof Iterable) {
JSONArray json = new JSONArray();
for (Object value : ((Iterable) object)) {
json.put(value);
}
return json;
} else {
return object;
}
}
/**
* list转json
* @param object
* @return
*/
public static JSONArray listToJson(Iterable object){
JSONArray json = new JSONArray();
for (Object value : object) {
json.put(value);
}
return json;
}
public static boolean isEmptyObject(JSONObject object) {
return object.names() == null;
}
public static Map
本文共计400个文字,预计阅读时间需要2分钟。
java/** * 工作中常用的JSON转换工具集 * * Created with IntelliJ IDEA. * User: yuyue * Date: 14-7-23 * Time: 下午7:51 * /public class JsonHelper { * * map转json,list转map,map转json的工具集合 * * @param object 是一个 对象 */
/**
* Created with IntelliJ IDEA.
* User: yuyue
* Date: 14-7-23
* Time: 下午7:51
*/
public class JsonHelper {
/**
* map转json
*
* @param object 是一个map
* @return
* @throws JSONException
*/
public static Object mapToJSON(Object object) throws JSONException {
if (object instanceof Map) {
JSONObject json = new JSONObject();
Map map = (Map) object;
for (Object key : map.keySet()) {
json.put(key.toString(), mapToJSON(map.get(key)));
}
return json;
} else if (object instanceof Iterable) {
JSONArray json = new JSONArray();
for (Object value : ((Iterable) object)) {
json.put(value);
}
return json;
} else {
return object;
}
}
/**
* list转json
* @param object
* @return
*/
public static JSONArray listToJson(Iterable object){
JSONArray json = new JSONArray();
for (Object value : object) {
json.put(value);
}
return json;
}
public static boolean isEmptyObject(JSONObject object) {
return object.names() == null;
}
public static Map

