Map、JSONObject、String相互转换

Map转JSONObject

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.59</version>
</dependency>
JSONObject info= JSONObject.parseObject(JSON.toJSONString(map));

JSONObject转Map:

JSONObject json = new JSONObject();//这里就不赋值了
Map<String, String> params = JSONObject.parseObject(json.toJSONString(), new TypeReference<Map<String, String>>(){});

String转JSONObject:

String s = "";//这里就不赋值了(字符串的格式需要key:value形式,否则会报错)
JSONObject jsonObject =JSONObject.parseObject(s);

String转Map:

<!-- 配置gson -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.2.4</version>
    </dependency>
String s = "";//这里就不赋值了(字符串的格式需要key:value形式,否则会报错)
Gson gson = new Gson();
Map<String, Object> map = new HashMap<>();
map = gson.fromJson(s, map.getClass());

Map转String:

Map<String,String> map = new HashMap<>();
map.toString();

转载于:https://blog.csdn.net/Efforts_To_Advanced/article/details/100104372?spm=1001.2014.3001.5506

你可能感兴趣的:(json格式转换,json)