学习Java第二十二天:1、认识JSON 2、生成JSON 3、解析JSON

目录

1、认识JSON

2、生成JSON

3、解析JSON


1、认识JSON

  1. 什么是JSON?

    JSON(JavaScript Object Notation ,JS对象简谱)是一种轻量级的数据交换格式。采用全完独立于编程语言的文本格式来存储和表示数据。

    • 完全独立的

    • 文本格式的

    • 轻量级的

  2. JSON的作用是什么?

    存储和表示数据的文本格式。

  3. 如何编写JSON?

    JSON是由2个元素组成

    第一个元素,json对象

    格式:{名称:数据值,名称:数据值,名称:数据值......}

    键值对中的键要有“ ”,键值对中的值时间日期和字符串类型的数据需要" "。

    我们将java对象转换成json对象以后的结果:

    public class Student{
        private int id;
        private String name;
        private int age;
        private String address;
        
        getXXX()
        setXXX()
    }
    //java对象
    Student stu1 = new Student();
    stu1.setId(1001);
    stu1.setName("张三");
    stu1.setAge(26);
    stu1.setAddress("深圳");
    ​
    //json对象
    {"id":1001,"name":"张三","age":26,"address":"深圳"}

    第二个元素:json数组

    格式:[具体的数据值/json对象]

    我们将java集合/数组转换成json数组以后的结果。

    public class Student{
        private int id;
        private String name;
        private int age;
        private String address;
        
        getXXX()
        setXXX()
    }
    //java对象
    Student stu1 = new Student();
    stu1.setId(1001);
    stu1.setName("张三");
    stu1.setAge(26);
    stu1.setAddress("深圳");
    //java对象
    Student stu2 = new Student();
    stu2.setId(1002);
    stu2.setName("李四");
    stu2.setAge(28);
    stu2.setAddress("杭州");
    //java对象
    Student stu3 = new Student();
    stu3.setId(1003);
    stu3.setName("王五");
    stu3.setAge(23);
    stu3.setAddress("广州");
    //list集合
    List<Student> studentList = new ArrayList<>();
    studentList.add(stu1);
    studentList.add(stu2);
    studentList.add(stu3);
    ​
    //json数组
    [
        {"id":1001,"name":"张三","age":26,"address":"深圳"},
        {"id":1002,"name":"李四","age":28,"address":"杭州"},
        {"id":1003,"name":"王五","age":23,"address":"广州"}
    ]
    ​
    //java数组转成json数组
    //java数组
    String[] str = {"张三","李四","王五"};
    //json数组
    ["张三","李四","王五"]

    我们以后所面临的json数据都是互相嵌套的,json数组中有json对象,json对象中有json数组。

    当我们得到一个极其复杂的json数据后,搞不清楚这个json数据的结构。

    我们可以利用工具得到明晰的json数据的结构。

    //java对象
    public class Main {
    ​
        public static void main(String[] args) throws Exception {
            Student stu1 = new Student();
            stu1.setId(1001);
            stu1.setName("张三");
            stu1.setAge(26);
            MyAddress myAddress1 = new MyAddress();
            myAddress1.setType("工作");
            myAddress1.setInfo("东环西路");
            MyAddress myAddress2 = new MyAddress();
            myAddress2.setType("家庭");
            myAddress2.setInfo("西环东路");
            MyAddress[] addressArray1 = {myAddress1,myAddress2};
            stu1.setAddress(addressArray1);
    ​
            Student stu2 = new Student();
            stu2.setId(1002);
            stu2.setName("李四");
            stu2.setAge(27);
            MyAddress myAddress3 = new MyAddress();
            myAddress3.setType("工作");
            myAddress3.setInfo("北环南路");
            MyAddress myAddress4 = new MyAddress();
            myAddress4.setType("家庭");
            myAddress4.setInfo("南环北路");
            MyAddress[] addressArray2 = {myAddress3,myAddress4};
            stu2.setAddress(addressArray2);
    ​
            List<Student> studentList = new ArrayList<>();
            studentList.add(stu1);
            studentList.add(stu2);
        }
    }
    //json对象
    [{
            "id": 1001,
            "name": "张三",
            "age": 26,
            "address": [{
                "type": "工作",
                "info": "东环西路"
            }, {
                "type": "家庭",
                "info": "西环东路"
            }]
        },
        {
            "id": 1002,
            "name": "李四",
            "age": 27,
            "address": [{
                "type": "工作",
                "info": "北环南路"
            }, {
                "type": "家庭",
                "info": "南环北路"
            }]
        }
    ]

2、生成JSON

  1. json-simple-1.1.jar第三方的开发包生成json数据(json-simple-1.1.jar)

    //java对象
    public class Main {
    ​
        public static void main(String[] args) throws Exception {
            Student stu1 = new Student();
            stu1.setId(1001);
            stu1.setName("张三");
            stu1.setAge(26);
            MyAddress myAddress1 = new MyAddress();
            myAddress1.setType("工作");
            myAddress1.setInfo("东环西路");
            MyAddress myAddress2 = new MyAddress();
            myAddress2.setType("家庭");
            myAddress2.setInfo("西环东路");
            MyAddress[] addressArray1 = {myAddress1,myAddress2};
            stu1.setAddress(addressArray1);
    ​
            Student stu2 = new Student();
            stu2.setId(1002);
            stu2.setName("李四");
            stu2.setAge(27);
            MyAddress myAddress3 = new MyAddress();
            myAddress3.setType("工作");
            myAddress3.setInfo("北环南路");
            MyAddress myAddress4 = new MyAddress();
            myAddress4.setType("家庭");
            myAddress4.setInfo("南环北路");
            MyAddress[] addressArray2 = {myAddress3,myAddress4};
            stu2.setAddress(addressArray2);
    ​
            List<Student> studentList = new ArrayList<>();
            studentList.add(stu1);
            studentList.add(stu2);
    ​
            String json1 = JSONHelper.createJson1(studentList);
            System.out.println(json1);
        }
    }
    ​
    public class JSONHelper {
        public static String createJson1(List<Student> studentList) {
            //创建studentList对应的json数组
            JSONArray jsonArray = new JSONArray();
            for (Student student : studentList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id",student.getId());
                jsonObject.put("name",student.getName());
                jsonObject.put("age",student.getAge());
                JSONArray jsonArray1 = new JSONArray();
                MyAddress[] address = student.getAddress();
                for (MyAddress myAddress : address) {
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("type",myAddress.getType());
                    jsonObject1.put("info",myAddress.getInfo());
                    jsonArray1.add(jsonObject1);
                }
                jsonObject.put("address",jsonArray1);
                jsonArray.add(jsonObject);
            }
            return jsonArray.toString();
        }
    }

     

  2. gson-2.8.0.jar第三方的开发包生成json数据(gson-2.8.9.jar)

    public class Main {
    ​
        public static void main(String[] args) throws Exception {
            Student stu1 = new Student();
            stu1.setId(1001);
            stu1.setName("张三");
            stu1.setAge(26);
            MyAddress myAddress1 = new MyAddress();
            myAddress1.setType("工作");
            myAddress1.setInfo("东环西路");
            MyAddress myAddress2 = new MyAddress();
            myAddress2.setType("家庭");
            myAddress2.setInfo("西环东路");
            MyAddress[] addressArray1 = {myAddress1,myAddress2};
            stu1.setAddress(addressArray1);
    ​
            Student stu2 = new Student();
            stu2.setId(1002);
            stu2.setName("李四");
            stu2.setAge(27);
            MyAddress myAddress3 = new MyAddress();
            myAddress3.setType("工作");
            myAddress3.setInfo("北环南路");
            MyAddress myAddress4 = new MyAddress();
            myAddress4.setType("家庭");
            myAddress4.setInfo("南环北路");
            MyAddress[] addressArray2 = {myAddress3,myAddress4};
            stu2.setAddress(addressArray2);
    ​
            List<Student> studentList = new ArrayList<>();
            studentList.add(stu1);
            studentList.add(stu2);
    ​
            String json2 = JSONHelper.createJson2(studentList);
            System.out.println(json2);
        }
    }
    ​
    public class JSONHelper {
        public static String createJson2(List<Student> studentList) {
            Gson gson = new Gson();
            String result = gson.toJson(studentList);
            return result;
        }
    }

     

  3. jackson第三方的开发包生成json数据(jackson-core-2.13.4.jar、jackson-databind-2.13.4.jar、json-simple-1.1.jar)

    public class Main {
    ​
        public static void main(String[] args) throws Exception {
            Student stu1 = new Student();
            stu1.setId(1001);
            stu1.setName("张三");
            stu1.setAge(26);
            MyAddress myAddress1 = new MyAddress();
            myAddress1.setType("工作");
            myAddress1.setInfo("东环西路");
            MyAddress myAddress2 = new MyAddress();
            myAddress2.setType("家庭");
            myAddress2.setInfo("西环东路");
            MyAddress[] addressArray1 = {myAddress1,myAddress2};
            stu1.setAddress(addressArray1);
    ​
            Student stu2 = new Student();
            stu2.setId(1002);
            stu2.setName("李四");
            stu2.setAge(27);
            MyAddress myAddress3 = new MyAddress();
            myAddress3.setType("工作");
            myAddress3.setInfo("北环南路");
            MyAddress myAddress4 = new MyAddress();
            myAddress4.setType("家庭");
            myAddress4.setInfo("南环北路");
            MyAddress[] addressArray2 = {myAddress3,myAddress4};
            stu2.setAddress(addressArray2);
    ​
            List<Student> studentList = new ArrayList<>();
            studentList.add(stu1);
            studentList.add(stu2);
    ​
            String json3 = JSONHelper.createJson3(studentList);
            System.out.println(json3);
        }
    }
    ​
    public class JSONHelper {
        public static String createJson3(List<Student> studentList) throws Exception {
            ObjectMapper objectMapper = new ObjectMapper();
            String string = objectMapper.writeValueAsString(studentList);
            return string;
        }
    }

     

3、解析JSON

  1. json-simple-1.1.jar第三方的开发包解析json数据(json-simple-1.1.jar)

    //解析Student.json: [{"id":1001,"name":"张三","age":26,"address":[{"type":"工作","info":"东环西路"},{"type":"家庭","info":"西环东路"}]},{"id":1002,"name":"李四","age":27,"address":[{"type":"工作","info":"北环南路"},{"type":"家庭","info":"南环北路"}]}]
    public class Main {
    ​
        public static void main(String[] args) throws Exception {
            List<Student> studentList = JSONHelper.getStudentList("E:\\JAVA\\workspace_idea\\XMLStudy\\XML\\src\\com\\liwq\\json\\Student.json");
            for (Student student : studentList) {
                System.out.println("id=" + student.getId() + "name=" + student.getName() + "age=" + student.getAge() + "address=" + student.getAddress());
            }
        }
    }
    ​
    public class JSONHelper {
    ​
        public static List<Student> getStudentList(String fileName) throws Exception {
            List<Student> result = new ArrayList<>();
            //读取数据
            FileReader fileReader = new FileReader(new File(fileName));
            BufferedReader reader = new BufferedReader(fileReader);
            String jsonString = reader.readLine();
            reader.close();
            //解析
            JSONParser jsonParser = new JSONParser();
            JSONArray parse = (JSONArray) jsonParser.parse(jsonString);
            for (int i = 0; i < parse.size(); i++) {
                Student student = new Student();
                JSONObject o = (JSONObject) parse.get(i);
                long idL = (Long) o.get("id");
                int id = (int)idL;
                student.setId(id);
                String name = (String) o.get("name");
                student.setName(name);
                long ageL = (Long) o.get("age");
                int age = (int)ageL;
                student.setAge(age);
                JSONArray address = (JSONArray) o.get("address");
                MyAddress[] addressArray = new MyAddress[address.size()];
                for (int i1 = 0; i1 < address.size(); i1++) {
                    MyAddress myAddress = new MyAddress();
                    JSONObject o1 = (JSONObject) address.get(i1);
                    String type = (String) o1.get("type");
                    myAddress.setType(type);
                    String info = (String) o1.get("info");
                    myAddress.setInfo(info);
                    addressArray[i1] = myAddress;
                }
                student.setAddress(addressArray);
                result.add(student);
            }
            return result;
        }
    }

     

  2. gson-2.8.0.jar第三方的开发解析json数据(gson-2.8.9.jar)

    //解析Student.json: [{"id":1001,"name":"张三","age":26,"address":[{"type":"工作","info":"东环西路"},{"type":"家庭","info":"西环东路"}]},{"id":1002,"name":"李四","age":27,"address":[{"type":"工作","info":"北环南路"},{"type":"家庭","info":"南环北路"}]}]
    public class Main {
    ​
        public static void main(String[] args) throws Exception {
            List<Student> studentList = JSONHelper.getStudentList("E:\\JAVA\\workspace_idea\\XMLStudy\\XML\\src\\com\\liwq\\json\\Student.json");
            for (Student student : studentList) {
                System.out.println("id=" + student.getId() + "name=" + student.getName() + "age=" + student.getAge() + "address=" + student.getAddress());
            }
        }
    }
    ​
    public class JSONHelper {
    ​
        public static List<Student> getStudentList(String fileName) throws Exception {
            Gson gson = new Gson();
            Type type = new TypeToken<List<Student>>() {
            }.getType();
            List<Student> studentList = gson.fromJson(new FileReader(new File(fileName)), type);
            return studentList;
        }
    }

  3. jackson第三方的开发包解析json数据(jackson-core-2.13.4.jar、jackson-databind-2.13.4.jar、json-simple-1.1.jar)

    //解析Student.json: [{"id":1001,"name":"张三","age":26,"address":[{"type":"工作","info":"东环西路"},{"type":"家庭","info":"西环东路"}]},{"id":1002,"name":"李四","age":27,"address":[{"type":"工作","info":"北环南路"},{"type":"家庭","info":"南环北路"}]}]
    public class Main {
    ​
        public static void main(String[] args) throws Exception {
            List<Student> studentList = JSONHelper.getStudentList("E:\\JAVA\\workspace_idea\\XMLStudy\\XML\\src\\com\\liwq\\json\\Student.json");
            for (Student student : studentList) {
                System.out.println("id=" + student.getId() + "name=" + student.getName() + "age=" + student.getAge() + "address=" + student.getAddress());
            }
        }
    }
    ​
    public class JSONHelper {
    ​
        public static List<Student> getStudentList(String fileName) throws Exception {
            List<Student> result = new ArrayList<>();
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(new File(fileName));
            for (int i = 0; i < jsonNode.size(); i++) {
                Student student = new Student();
                JsonNode jsonNode1 = jsonNode.get(i);
                int id = jsonNode1.get("id").asInt();
                student.setId(id);
                String name = jsonNode1.get("name").asText();
                student.setName(name);
                int age = jsonNode1.get("age").asInt();
                student.setAge(age);
                JsonNode address = jsonNode1.get("address");
                MyAddress[] myAddresses = new MyAddress[address.size()];
                for (int i1 = 0; i1 < address.size(); i1++) {
                    MyAddress myAddress = new MyAddress();
                    JsonNode jsonNode2 = address.get(i1);
                    String type = jsonNode2.get("type").asText();
                    myAddress.setType(type);
                    String info = jsonNode2.get("info").asText();
                    myAddress.setInfo(info);
                    myAddresses[i1] = myAddress;
                }
                student.setAddress(myAddresses);
                result.add(student);
            }
            return result;
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

互联网农民工001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值