0、JSON使用阿里的 fastJson 为依赖包
1、String转JSONObject
JSONObject jSONObject = JSONObject.parseObject(String);
2、String转JSONArray
JSONArray jsonArray= JSONArray.parseArray(String);
3、实例
json串:
{ "data": { "route": { "destination": "109.56350818276404,39.575900296924715", "paths": [{ "distance": 200067, "steps": [{ "action": "右转", "assistant_action": "", "cities": [{ "adcode": "610802" }, { "adcode": "610802" } ] }, { "action": "左转", "assistant_action": "", "cities": [{ "adcode": "610802" }, { "adcode": "610802" } ] } ], "strategy": "时间最短" } ] }, "count": 1 }, "errmsg": "OK" }
解析代码:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; /** * @Date 2021/8/13 11:15 * @Version 1.0 */ public class TestJsonParse { public static void main(String[] args) { String jsonStr = "{" + " "errmsg": "OK"," + " "data": {" + " "route": {" + " "destination": "109.56350818276404,39.575900296924715"," + " "paths": [{" + " "distance": 200067," + " "steps": [{" + " "action": "右转"," + " "assistant_action": ""," + " "cities": [{" + " "adcode": "610802"" + " }, {" + " "adcode": "610802"" + " }" + " ]" + " }, {" + " "action": "左转"," + " "assistant_action": ""," + " "cities": [{" + " "adcode": "610802"" + " }, {" + " "adcode": "610802"" + " }" + " ]" + " }" + " ]," + " "strategy": "时间最短"" + " }" + " ]" + " }," + " "count": 1" + " }" + "}"; // 第一层 JSONObject one = JSONObject.parseObject(jsonStr); System.out.println("data: " + one.get("errmsg").toString()); // 第二层 JSONObject two = JSON.parseObject( one.get("data").toString()); // 第三层 JSONObject three = JSON.parseObject( two.get("route").toString()); // 第四层 数组 JSONArray four = JSON.parseArray( three.get("paths").toString()); // 第五层 获取数组中,第一个对象 JSONObject five = four.getJSONObject(0); System.out.println("distance: " + five.get("distance")); } }