import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
public class JsonToMap {
/**
* fastjson的使用(处理json字符串、json数组)
* 练习1:将json字符串转化成map,
* 字符串:{"username":"qzcsbj", "password":"123456"}
*/
public static void main(String[] args) {
String str = "{\"username\":\"qzcsbj\", \"password\":\"123456\"}";
//方法一
Map maps = (Map) JSON.parse(str);
System.out.println("使用JSON类来解析json字符串:");
for (Object map:maps.entrySet()) {
System.out.println(((Map.Entry)map).getKey() + " " + ((Map.Entry)map).getValue());
}
//方法二
Map maps1 = JSON.parseObject(str);
System.out.println("使用JSON类的parseObject解析json字符串:");
for (Object key:maps1.keySet()) {
System.out.println("key:" + key + ",value:" + maps1.get(key));
}
//方法三
Map maps2 = JSON.parseObject(str,Map.class);
System.out.println("使用JSON类,指定解析类,解析json字符串:");
for (Object key:maps2.keySet()) {
System.out.println("key:" + key + "->value:" + maps2.get(key));
}
//方法四
Map maps3 = (Map)JSONObject.parse(str);
System.out.println("使用JSONObject类的parse解析json字符串:");
for (Object map:maps3.entrySet()) {
System.out.println(((Map.Entry)map).getKey() + " " + ((Map.Entry)map).getValue());
}
//方法五
Map maps4 = JSONObject.parseObject(str);
System.out.println("使用JSONObject类的parseObject解析json字符串:");
for (Object map:maps4.entrySet()) {
System.out.println(((Map.Entry)map).getKey() + " " + ((Map.Entry)map).getValue());
}
//方法六
Map maps5 = JSONObject.parseObject(str,Map.class);
System.out.println("使用JSONObject类的parseObject,指定解析类,解析json字符串:");
for (Object map:maps5.entrySet()) {
System.out.println(((Map.Entry)map).getKey() + " " + ((Map.Entry)map).getValue());
}
//map转化成json
JSON json = (JSON)JSONObject.toJSON(maps1);
System.out.println(json);
//map转化成json
JSON json1 = (JSON)JSON.toJSON(maps1);
System.out.println(json1);
}
}
依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.29</version>
</dependency>