json作为一种比较常用的数据交换格式,一般在前后台应用交互的时候经常会用到 json格式数据。
一般涉及到的有关于json与字符串格式的转换以及接送与对象格式的转换。
这里介绍一下阿里的开源JSON解析库 fastjson 。
maven 坐标
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
常用的方法有
String s = "{\"name\":\"ying\"}";
//将string字符串转换为Json对象
JSONObject object = JSON.parseObject(s);
//利用键值对的方式获取到值
System.out.println(object.get("name"));
//将map转换为json字符串
Map<Integer, Object> map = new HashMap<Integer,Object>();
map.put(1, "one");
map.put(2, "two");
map.put(3, new ArrayList<String>().add("three"));
String jsonString = JSON.toJSONString(map);
//下面为源码中方法,该方法可以传入一个对象
public static String toJSONString(Object object) {
return toJSONString(object, emptyFilters);
}
//转换为json数组
String str2="[{\"name\":\"ying\"},{\"age\":\"18\"}]";
JSONArray jsonArray = JSONArray.parseArray(str2);
//转换为具体的对象比如转换为一个具体JavaBean对象
String str3="";
//clazz 为类的字节码对象,此方法得到具体对象
JSONObject.parseObject(str3,clazz);