使用alibaba的fastjson
1、Map转json
Map<String, Object> map = new HashMap<String, Object>();
JSONObject json = new JSONObject(map);
2、Map转String
Map<String, Object> map = new HashMap<>();
String s = JSONObject.toJSONString(map);
3、JSON转String
JSONObject json = new JSONObject();
json.toJSONString();
4、JSON转Map
JSONObject json = new JSONObject();
Map<String, Object> map = (Map<String, Object>)json;
5、String转json
String str = "{\"username\":\"dsad\",\"qwewqe\":\"123\"}";
JSONObject json = JSONObject.parseObject(str);
使用google
maven依赖
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
1、Map转json
Map<String,String> map = new HashMap<String,String>();
String json=JSON.toJSONString(map);
System.out.println(json);