/**
     * 解析对象形式的json字符串
     */
    public static void test1() {
        String jsonStr = "{\"JACKIE_ZHANG\":\"张学友\",\"ANDY_LAU\":\"刘德华\",\"LIMING\":\"黎明\",\"Aaron_Kwok\":\"郭富城\"}";
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        System.out.println(jsonObject.get("JACKIE_ZHANG"));
        System.out.println(jsonObject.get("ANDY_LAU"));
        System.out.println(jsonObject.get("LIMING"));
        System.out.println(jsonObject.get("Aaron_Kwok"));
    }

    /**
     * 解析集合形式的json字符串
     */
    public static void test2() {
        String jsonStr = "[{\"JACKIE_ZHANG\":\"张学友\"},{\"ANDY_LAU\":\"刘德华\"},{\"LIMING\":\"黎明\"},{\"Aaron_Kwok\":\"郭富城\"}]";
        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
        JSONObject jsonObject = JSONObject.parseObject(jsonArray.get(0)+"");
        System.out.println(jsonObject.get("JACKIE_ZHANG"));
    }

    /**
     *  将对象转换为JSON字符串
     */
    public static void test3() {
        UserInfo info = new UserInfo();
        info.setName("zhangsan");
        info.setAge(24);
        String str_json = JSON.toJSONString(info);
        System.out.println("JSON=" + str_json);
    }

    /**
     * 将复杂的字符串转换成字符串
     */
    public static void test4() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("username", "zhangsan");
        map.put("age", 24);
        map.put("sex", "男");

        // map集合
        HashMap<String, Object> temp = new HashMap<String, Object>();
        temp.put("name", "xiaohong");
        temp.put("age", "23");
        map.put("girlInfo", temp);

        // list集合
        List<String> list = new ArrayList<String>();
        list.add("爬山");
        list.add("骑车");
        list.add("旅游");
        map.put("hobby", list);

        String jsonString = JSON.toJSONString(map);
        System.out.println("JSON=" + jsonString);
    }

    /**
     * 将json字符串转换成bean对象
     */
    public static void test5() {
        String json = "{\"name\":\"chenggang\",\"age\":24}";
        UserInfo userInfo = JSON.parseObject(json, UserInfo.class);
        System.out.println("name:" + userInfo.getName() + ", age:" + userInfo.getAge());
    }


    /** 泛型的反序列化 */
    public static void test6() {
        String json = "{\"user\":{\"name\":\"zhangsan\",\"age\":25}}";
        Map<String, UserInfo> map = JSON.parseObject(json, new TypeReference<Map<String, UserInfo>>() {
        });
        System.out.println(map.get("user").getAge());
    }

    /**
     * 时间的序列化
     */
    public static void test7() {
        Date date = new Date();
        // 输出毫秒值
        System.out.println(JSON.toJSONString(date));
        // 默认格式为yyyy-MM-dd HH:mm:ss
        System.out.println(JSON.toJSONString(date, SerializerFeature.WriteDateUseDateFormat));
        // 根据自定义格式输出日期
        System.out.println(JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat));
    }

 

posted on 2017-09-14 19:06  zhangjinru123  阅读(148)  评论(0编辑  收藏  举报