1.fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.42</version>
</dependency>
JSONObject jsonObject = JSONObject.parseObject(json);
return (String) jsonObject.get("access_token");
2.substring
仅限于指定格式
public void getTokenFromJSON() {
String jsonString = "{\"access_token\":\"54871544ED15874564115\",\"expires_in\":\"86400\"}";
// 移除最外层“{“ ”}”
jsonString = jsonString.substring(1, jsonString.length() - 1);
//分割键值对,得到键值对数组
String[] keyValueList = jsonString.split(",");
Map<String, String> result = new HashMap<>();
for (String list : keyValueList) {
// 使用冒号分割键和值
String[] keyAndValue = list.trim().split(":");
// 移除键和值周围的引号
String key = keyAndValue[0].substring(1, keyAndValue[0].length() - 1);
String value = keyAndValue[1].substring(1, keyAndValue[1].length() - 1);
// 将键值对添加到Map中
result.put(key, value);
}
// 访问access_token
String access_token = result.get("access_token");
String expires_in = result.get("expires_in");
System.out.println("access_token = " + access_token);
System.out.println("expires_in = " + expires_in);
}