alibaba的fastjson使用心得

版权声明:未经允许,不得转载 https://blog.csdn.net/dhj199181/article/details/84631175

JSON数据格式在开发中我们会经常用到,是一种很轻量级数据格式,之前的工作中只顾着使用,却从来没仔细关注过他的底层是怎么实现的,今天帮同事解决问题的使用,无意中去看了一下他的底层实现,才恍然大悟,原来是这么回事。

首先我们看一下他的构造函数:

 private final Map<String, Object> map;

    public JSONObject(){
        this(DEFAULT_INITIAL_CAPACITY, false);
    }

    public JSONObject(Map<String, Object> map){
        this.map = map;
    }

    public JSONObject(boolean ordered){
        this(DEFAULT_INITIAL_CAPACITY, ordered);
    }

    public JSONObject(int initialCapacity){
        this(initialCapacity, false);
    }

    public JSONObject(int initialCapacity, boolean ordered){
        if (ordered) {
            map = new LinkedHashMap<String, Object>(initialCapacity);
        } else {
            map = new HashMap<String, Object>(initialCapacity);
        }
    }

当我们使用JSONObject jsonObject3 = new JSONObject();的时候,他实际上默认的为我们创建了一个HashMap对象来保存对象,使用JSONObject jsonObject3 = new JSONObject(true)时实际上帮我们创建了一个LinkedHashMap对象,接下来一系列的操作自然也就是使用了Map接口里的相关方法;

JSON格式数据:

{"we3":"3434","fgg":[{"cxx":[{"trrr":"233"}],"tyy":34,"name":"zzz","id":"a"},{"cxx":[{"trrr":"23eee3"}],"tyy":3544,"name":"rrr","id":"ae"}],"we":"344"}

比如使用put方法,看下源码,实际上是直接使用的map的put方法,但是这里没有做任何判断:

    public Object put(String key, Object value) {
        return map.put(key, value);
    }

使用replace方法,看下源码,实际上是先判断了一下map集合中有没有对应的值,有则再使用的map的put方法,没有则不降key和value放到map中:

    default V replace(K key, V value) {
        V curValue;
        if (((curValue = get(key)) != null) || containsKey(key)) {
            curValue = put(key, value);
        }
        return curValue;
    }

使用remove方法,看下源码,实际上是直接使用的map的remove方法

  public Object remove(Object key) {
        return map.remove(key);
    }

猜你喜欢

转载自blog.csdn.net/dhj199181/article/details/84631175