使用 fastjson-1.2.4.jar,一个解析json字符串jar包,由阿里巴巴工程师开发。
User.java
package com.godcin.test.bean; import java.util.List; public class User { private String name; private int age; private List<String> habits; 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; } public List<String> getHabits() { return habits; } public void setHabits(List<String> habits) { this.habits = habits; } }
jsonArrayTest.java
package com.godcin.test.json; import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.godcin.test.bean.User; public class jsonArrayTest { public static void main(String[] args) { User user1 = new User(); user1.setName("张三"); user1.setAge(18); List<String> habits1 = new ArrayList<String>(); habits1.add("抽烟"); habits1.add("喝酒"); user1.setHabits(habits1); User user2 = new User(); user2.setName("李四"); user2.setAge(18); List<String> habits2 = new ArrayList<String>(); habits2.add("打牌"); habits2.add("唱歌"); user2.setHabits(habits2); List<User> users=new ArrayList<User>(); users.add(user1); users.add(user2); JSONArray jsonArray=new JSONArray();//1、创建JSONArray jsonArray.addAll(users);//2、把JSONArray添加List,List<User>转JSONArray System.out.println(jsonArray.get(0));//输出结果|[email protected] System.out.println(jsonArray.get(1));//输出结果|[email protected] System.out.println("姓名:"+((User)jsonArray.get(0)).getName());//输出结果|姓名:张三 System.out.println("爱好:"+((User)jsonArray.get(1)).getHabits());//输出结果|爱好:[打牌, 唱歌] String jsonStr=jsonArray.toJSONString();//3、JSONArray转化json字符串 System.out.println(jsonStr);//输出结果|[{"age":18,"habits":["抽烟","喝酒"],"name":"张三"},{"age":18,"habits":["抽烟","喝酒"],"name":"张三"}] users=JSON.parseArray(jsonStr, User.class);//json字符串转List<User> System.out.println(users);//输出结果 |[[email protected], [email protected]] } }
时间: 2024-10-11 12:59:45