JSON串的元素追加和合并

import com.alibaba.fastjson.JSONObject;

/**
 * create by 86159 on 2021/1/9
 */
public class JsonTest {
    public static void main(String[] args) {
        JSONObject json = new JSONObject();
        json.put("name","zhangsan");
        json.put("age",18);
        System.out.println(json.toString());
        //{"name":"zhangsan","age":18}


        //在原有的json串基础上追加属性,直接追加,无需转map,map  put后再转json
        json.put("sex","男");
        System.out.println(json.toString());
        //{"sex":"男","name":"zhangsan","age":18}

        //两个json串合并成一个json串
        JSONObject jsonOne = new JSONObject();
        JSONObject jsonTwo = new JSONObject();
        jsonOne.put("name","lisi");
        jsonOne.put("age",20);

        jsonTwo.put("sex","女");
        jsonTwo.put("class","java");
        jsonTwo.put("score",100);

        // 使用putAll将两个json串中所有元素合并到新的json串中
        JSONObject jsonTree = new JSONObject();
        jsonTree.putAll(jsonOne);
        jsonTree.putAll(jsonTwo);
        System.out.println(jsonTree.toString());
        //{"score":100,"sex":"女","name":"lisi","class":"java","age":20}
    }

}

你可能感兴趣的:(java笔记,json,java)