Java將字符串轉換為jsonObject對象並獲取json數組格式


代碼如下:

package com.example;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


public class JsonToLibTest {


    public static void main(String[] args) {
        String str = "{\"cells\": [{\"shape\": \"rect\",\"id\": \"4df7abde-19c3-41e0-a7b3-80917098acb5\",\"visible\": false,\"zIndex\": 23,\"parent\": \"e3ed22a5-8cf4-45a9-835d-43ce4e47bf55\"},{\"shape\": \"rect\",\"id\": \"96e6ff54-db70-4c55-a09d-66b20b42acc7\",\"visible\": false,\"zIndex\": 24,\"parent\": \"e3ed22a5-8cf4-45a9-835d-43ce4e47bf55\"}]}";
        //字符串轉換為JSONObject對象
        JSONObject jsonObject = JSONObject.parseObject(str);
        JSONArray jsonArray = null;
        //獲取json對象並轉換為數組
        jsonArray = jsonObject.getJSONArray("cells");
        for (int i = 0; i < jsonArray.size(); i++) {
            //打印數組
            System.out.println(jsonArray.getJSONObject(i));
        }
        //獲取對象中元素屬性
        Object shape = jsonArray.getJSONObject(0).get("shape");
        //打印實體屬性
        System.out.println(shape.toString());

    }
}

 

打印結果:

{"parent":"e3ed22a5-8cf4-45a9-835d-43ce4e47bf55","visible":false,"shape":"rect","id":"4df7abde-19c3-41e0-a7b3-80917098acb5","zIndex":23}
{"parent":"e3ed22a5-8cf4-45a9-835d-43ce4e47bf55","visible":false,"shape":"rect","id":"96e6ff54-db70-4c55-a09d-66b20b42acc7","zIndex":24}
rect

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM