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