JsonUtil

来源:互联网 发布:unity3d与android交互 编辑:程序博客网 时间:2024/05/24 06:27

Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Fastjson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Fastjson Goals

Provide best performance in server side and android client
Provide simple toJSONString() and parseObject() methods to convert Java objects to JSON and vice-versa
Allow pre-existing unmodifiable objects to be converted to and from JSON
Extensive support of Java Generics
Allow custom representations for objects
Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)

import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.serializer.SerializerFeature;import java.util.HashMap;import java.util.List;import java.util.Map;/** * JSON tool  *  */public class JsonUtil {    public static String objectToJson(Object obj) {        return JSON.toJSONString(obj);    }    public static String objectToJsonWithDateFormat(Object obj, String timeFormat, SerializerFeature serializerFeature) {        return JSON.toJSONStringWithDateFormat(obj, timeFormat, serializerFeature);    }    public static <T> List<T> jsonToList(String jsonStr, Class<T> clazz) {        return JSON.parseArray(jsonStr, clazz);    }    public static Map<String, Object> jsonToMap(String jsonStr) {        return JSON.parseObject(jsonStr);    }    public static <T> T jsonToObject(String jsonStr, Class<T> clazz) {        return JSON.parseObject(jsonStr, clazz);    }    @SuppressWarnings(value={"rawtypes"})    public static <T> List mapKeyGetList(Map map, String key, Class<T> clazz) {        JSONArray arr = (JSONArray)map.get(key);        return JSON.parseArray(arr.toString(), clazz);    }    @SuppressWarnings(value={"rawtypes"})    public static Map[] mapKeyGetMap(Map map, String key) {        List<Map> list = mapKeyGetList(map, key, Map.class);        return list.toArray(new HashMap[list.size()]);    }}
原创粉丝点击