package com.lemon.json;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: Lemon
 * @description:
 * @author: ray
 * @create: 2022-09-21 17:23
 **/
public class Demo {
    public static void main(String[] args) {
        /*
         * 静态方法的特点：不需要创建对象，直接用类名就可以调用
         */

        // 1、字符串转对象
        String json = "{\"name\":\"张三\",\"age\":\"18\"}";
        Student student = JSONObject.parseObject(json, Student.class);
        System.out.println(student.getName() + "=" + student.getAge());

        Map map1 = JSONObject.parseObject(json, Map.class);
        System.out.println("map1:" + map1);


        // 2、对象转字符串
        Student student1 = new Student("lisi", 20);
        String s = JSONObject.toJSONString(student1);
        System.out.println(s);

        // 3、HashMap
        HashMap<String, String> map = new HashMap<>();
        map.put("code", "200");
        map.put("msg", "success");
        System.out.println(JSONObject.toJSONString(map));

        // 4、字符串数组转成一个list集合
        String json2 = "[{\"age\":20,\"name\":\"李四\"},{\"age\":18,\"name\":\"王五\"}]";
        List<Student> list = JSONObject.parseArray(json2, Student.class);
        for (Student stu : list) {
            System.out.println(stu.getName() + "=" + stu.getAge());
        }


    }
}
