import com.alibaba.fastjson.JSON;
import java.util.List;
import java.util.Map;
/**
- json工具类
*/
public class FastJsonUtils {
/**
* 将JSON字符串转为对象
*
* @param text
* @param clazz
* @return
*/
public static <T> T parseObject(Object text, Class<T> clazz) {
if (text == null) {
return null;
}
if (text.toString().length() == 0) {
return null;
}
return JSON.parseObject(text.toString(), clazz);
}
/**
* 讲对象转为JSON字符串
*
* @param object
* @return
*/
public static String toJSONString(Object object) {
return JSON.toJSONString(object);
}
public static void main(String[] args) {
//把下列JSON解析成一个Map
String json = "{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\",\"key4\":\"value4\"}";
Map<String, String> map = parseObject(json, Map.class);
System.out.println();
//把下列JSON解析成一个List
String json1 = "[\"value1\",\"value2\",\"value3\",\"value4\"]";
List<String> list = parseObject(json1, List.class);
System.out.println();
//把下列JSON解析成一个List
String json3 = "[{\"k1\":1,\"k2\":2},{\"k1\":1,\"k2\":2}]";
List<Map<String, Integer>> list1 = parseObject(json3, List.class);
System.out.println();
//把下列JSON解析成一个Map
String json4 = "{\"k1\":[\"v1\",\"v2\"],\"k2\":[\"v1\",\"v2\"]}";
Map<String, List<String>> map1 = parseObject(json4, Map.class);
System.out.println();
//把下列JSON解析成一个Map
String json5 = "{\"k1\":{\"k1\":{\"k1\":\"v1\",\"k2\":\"v2\"},\"k2\":{\"k1\":\"v1\",\"k2\":\"v2\"}},\"k2\":{\"k1\":{\"k1\":\"v1\",\"k2\":\"v2\"},\"k2\":{\"k1\":\"v1\",\"k2\":\"v2\"}}}";
Map<String, Map<String, Map<String, String>>> map2 = parseObject(json5, Map.class);
System.out.println();
}
}
在线JSON校验格式化工具http://www.bejson.com/