Json 解析 拼接 转换 fastjson的简单使用

学习是一个自我成长的过程,每天比昨天的自己进步,就没有虚度!

    /**
     * @author Lucky
     * @Description  json字符串转java代码
     * @Date 11:21 2018/5/8
     * @Param []
     * @return void
     **/
    public static void jsonToJava(){
        System.out.println("json字符串转java代码");
        String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";
        JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonStr);
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");
        System.err.println("json--->java \n username="+username+"\t passwor="+password);
    }

/**
     * @author Lucky
     * @Description java代码解析为json字符串
     * @Date 11:22 2018/5/8
     * @Param []
     * @return void
     **/
    public static void javaToJson(){
        System.out.println("java代码解析为json字符串");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "Lucky");
        jsonObject.put("age", 18);
        jsonObject.put("sex", "男");
        System.err.println("java--->json \n " + jsonObject.toString());
    }

这里写图片描述

/**
     * @author Lucky
     * @Description 解析嵌套字符串
     * @Date 11:27 2018/5/8
     * @Param []
     * @return void
     **/
    public static void analyticStr(){
        String JsonMulti = "{'name':'tom','score':{'Math':98,'English':90}}";
        JSONObject obj = (JSONObject) JSONObject.parse(JsonMulti);
        System.err.println("name = " + obj.get("name"));
        System.err.println("score = " + obj.get("score"));

        JSONObject scoreObj = (JSONObject) obj.get("score");
        System.err.println("Math score = " + scoreObj.get("Math"));
        System.err.println("English score = " + scoreObj.get("English"));
    }

这里写图片描述

/**
     * @author Lucky
     * @Description 构造一个json字符串
     * @Date 14:10 2018/5/8
     * @Param []
     * @return void
     **/
    public static void creatJsonStr(){
        JSONObject obj = new JSONObject();
        obj.put("name", "Lucky");
        obj.put("age", 19);
        // 子对象
        JSONObject objContact = new JSONObject();
        objContact.put("tel", "18987654321");
        objContact.put("email", "[email protected]");
        obj.put("contact", objContact);
        // 子数组对象
        JSONArray scoreArr = new JSONArray();
        JSONObject objEnglish = new JSONObject();
        objEnglish.put("course", "chainese");
        objEnglish.put("result", 100);
        objEnglish.put("level", "A");
        JSONObject objMath = new JSONObject();
        objMath.put("course", "math");
        objMath.put("result", 50);
        objMath.put("level", "D");
        scoreArr.add(objEnglish);
        scoreArr.add(objMath);
        obj.put("score", scoreArr);
        System.err.println(obj.toString());
    }

这里写图片描述

我爱你
愿你所有的温柔
都能换来岁月的情深意浓
可以不必回首
相扶白头!

猜你喜欢

转载自blog.csdn.net/shasiqq/article/details/80239972
今日推荐