- 工作中經常會用到數據的轉換,因此總結一下
如下Json格式的字符串
{
"status": 0,
"result": {
"location": {
"areacode": "101091107",
"name": "海港區",
"country": "中國",
"path": "海港區,秦皇島市,河北省,中國"
},
"realtime": {
"text": "晴",
"code": "00",
"temp": 29.1,
"wind_class": "2級",
"wind_dir": "西南風"
},
"last_update": "2020-06-19 11:26"
}
}
- String類型轉JSONObject,下面有兩種方式可以進行轉換
1、使用alibaba的com.alibaba.fastjson.JSONObject進行轉換
import com.alibaba.fastjson.JSONObject;
/**
* 字符串轉JSONObject
* @param str 傳入的json格式字符串
* @return JSONObject
*/
public static JSONObject stringToJSONObject(String str){
JSONObject jsonObject = JSONObject.parseObject(str);
return jsonObject;
}
2、使用org.json.JSONObject進行轉換
import org.json.JSONObject;
/**
* 字符串轉JSONObject
* @param str 傳入的json格式字符串
* @return JSONObject
*/
public static JSONObject stringToJSONObject(String str){
//通過org.json.JSONObject類進行String轉JSONObject
JSONObject jsonObject1 = new JSONObject();
return jsonObject;
}
轉換完成後,獲取key中的value值,如下代碼:獲取result中的realtime的值,可以將其轉換成string也可以將其轉成JSONObject
String jsonStr= jsonObject.getJSONObject("result").get("realtime").toString();