Map、JSON、String之间的转换

使用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); 
 

猜你喜欢

转载自blog.csdn.net/qq_40386113/article/details/112577349
今日推荐