首頁  >  文章  >  Java  >  java中JSONArray互相轉換List怎麼實現

java中JSONArray互相轉換List怎麼實現

WBOY
WBOY轉載
2023-05-04 17:25:0615287瀏覽

1:JSONArray轉List

JSONArray字串轉List

//初始化JSONArray
JSONArray array=new JSONArray();
array.add(0,"a");
array.add(1,"b");
array.add(2,"c");
 
List<String> list = JSONObject.parseArray(array.toJSONString(),String.class);
 
System.out.println(list.toString());

輸出結果:
[a, b, c]

JSONArray物件轉List

//初始化JSONArray
JSONArray jsonArray = JSONArray.parseArray("[{\"name\":\"zhangsan\",\"age\":18},{\"name\":\"lisi\",\"age\":23}]");
//打印jsonArray
System.out.println(jsonArray.toJSONString());
//转List
List<Body> list = JSONArray.parseArray(jsonArray.toJSONString(), Body.class);
//打印List<Body>
System.out.println(list.toString());

Body.class程式碼:

/**
*测试实体类
**/
static class Body implements Serializable {
        private static final long serialVersionUID = 1L;
        private String name;
        private int age;
 
        public String getName() {
            return name;
        }
 
        public void setName(String name) {
            this.name = name;
        }
 
        public int getAge() {
            return age;
        }
 
        public void setAge(int age) {
            this.age = age;
        }
 
        @Override
        public String toString() {
            return "Body{" +
                    "name=&#39;" + name + &#39;\&#39;&#39; +
                    ", age=" + age +
                    &#39;}&#39;;
        }
}

輸出結果:
[{"name":"zhangsan","age":18}, {"name":"lisi","age":23}]
[Body{name='zhangsan', age=18}, Body{name='lisi', age=23}]

2:List轉JSONArray

List<T> list = new ArrayList<T>();
JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list));

以上是java中JSONArray互相轉換List怎麼實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除