开发中经常遇到将字符串转成json和字符串转成json属组的方法,网上搜到的方法,好多都是不好用的,今天这里记录一下方便自己今后查看,也提供给需要的人。
依赖:
<!-- 处理json --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.56</version> </dependency>
代码:
public static void main(String[] args) { //字符串转json对象 String jsonStr = "{ expires_in: 2592000,\n" + "refresh_token: \"122.2582432a1cf40bc91ca31c10b5a6c038.Y3l6ETFhyjmS8ABFNRv3cPcJzKO-Pl9M4TCnUpx.LHh1Vw\",\n" + "access_token: \"121.fd4b4277dba7a65a51cf370d0e83f567.Y74pa1cYlIOT_Vdp2xuWOqeasckh1tWtxT9Ouw5.LPOBOA\",\n" + "session_secret: \"\",\n" + "session_key: \"\",\n" + "scope: \"basic netdisk\"\n" + "}"; JSONObject json=(JSONObject) JSONObject.toJSON(JSON.parse(jsonStr)); System.out.println("access_token:"+json.getString("access_token")); //字符串转json对象数组 String jsonArrayStr ="{ \n" + " \"users\": [\n" + " {\n" + " \"id\": \"1\",\n" + " \"name\": \"张三\",\n" + " },\n" + " {\n" + " \"id\": \"2\",\n" + " \"name\": \"李四\",\n" + " } \n" + " ]\n" + "}"; JSONObject jsonTemp=(JSONObject) JSONObject.toJSON(JSON.parse(jsonArrayStr)); JSONObject jsnobject = new JSONObject(jsonTemp); JSONArray jsonArray = jsnobject.getJSONArray("users"); for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); System.out.println(jsonObject.get("name")); } }
输出结果:
标签:name,JSONObject,token,json,转成,字符串 From: https://www.cnblogs.com/csjoz/p/16785238.html