All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.zodiac.sdk.json.JSONNode Maven / Gradle / Ivy

There is a newer version: 1.5.17
Show newest version
package org.zodiac.sdk.json;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

import org.zodiac.sdk.json.core.*;
import org.zodiac.sdk.json.ext.Act1;
import org.zodiac.sdk.json.ext.Act2;
import org.zodiac.sdk.json.from.FromHandler;
import org.zodiac.sdk.json.to.ToHandler;
import org.zodiac.sdk.toolkit.info.BuildMetaInfo;

public class JSONNode {

    /*内部配置*/
    protected JSONOptions _o;
    /*内部数据*/
    protected JSONNodeData _d;

    public static String version() {
        return BuildMetaInfo.buiildVersion();
    }

    public JSONNode() {
        _o = JSONOptions.def();
        _d = new JSONNodeData(this);
    }

    public JSONNode(JSONOptions options) {
        _d = new JSONNodeData(this);

        if(options ==null){
            _o = JSONOptions.def();
        }else {
            _o = options;
        }
    }

    public static JSONNode newValue(){
        return new JSONNode().asValue();
    }

    public static JSONNode newObject(){
        return new JSONNode().asObject();
    }

    public static JSONNode newArray(){
        return new JSONNode().asArray();
    }

    /**
     * Json path select
     *
     * @param jpath json path express
     * @param useStandard use standard mode(default: false)
     * @param cacheJpath cache json path parsing results
     * @return JSONNode
     */
    public JSONNode select(String jpath,  boolean useStandard, boolean cacheJpath) {
        return JSONPath.eval(this, jpath, useStandard, cacheJpath);
    }

    public JSONNode select(String jpath,  boolean useStandard) {
        return select(jpath, useStandard, true);
    }

    public JSONNode select(String jpath) {
        return select(jpath, false);
    }

    public JSONNode asObject() {
        _d.tryInitObject();
        return this;
    }

    public JSONNode asArray() {
        _d.tryInitArray();
        return this;
    }

    public JSONNode asValue() {
        _d.tryInitValue();
        return this;
    }

    public JSONNode asNull() {
        _d.tryInitNull();
        return this;
    }

    public JSONNodeData nodeData() {
        return _d;
    }

    public JSONNodeType nodeType() {
        return _d.nodeType;
    }

    public JSONNode options(JSONOptions opts) {
        if (opts != null) {
            _o = opts;
        }
        return this;
    }

    public JSONOptions options(){
        return _o;
    }

    public JSONNode build(Act1 fun) {
        fun.run(this);
        return this;
    }

    ////////////////////
    //
    // 值处理
    //
    ////////////////////

    public JSONValue val() {
        return asValue()._d.value;
    }

    public JSONNode val(Object val) {
        if (val == null) {
            _d.tryInitNull();
        } else if (val instanceof JSONNode) {
            /*支持数据直接copy*/
            _d.tryInitNull();
            _d = ((JSONNode) val)._d;
        } else if (val instanceof Map || val instanceof Collection) {
            _d.tryInitNull();
            _d = buildVal(val)._d;
        } else {
            _d.tryInitValue();
            _d.value.set(val);
        }
        return this;
    }

    public String getString() {
        if (isValue()) {
            return _d.value.getString();
        } else {
            if (isArray()) {
                return toJson();
            }

            if (isObject()) {
                return toJson();
            }

            return _o.nullString();
        }
    }

    public short getShort() {
        if (isValue())
            return _d.value.getShort();
        else
            return 0;
    }

    /**
     * 获取节点值并以 int 输出。
     * @return int
     */
    public int getInt() {
        if (isValue())
            return _d.value.getInt();
        else
            return 0;
    }

    public long getLong() {
        if (isValue())
            return _d.value.getLong();
        else
            return 0;
    }

    public float getFloat() {
        if (isValue())
            return _d.value.getFloat();
        else
            return 0;
    }

    public double getDouble() {
        if (isValue())
            return _d.value.getDouble();
        else
            return 0;
    }

    public double getDouble(int scale) {
        double temp = getDouble();

        if (temp == 0)
            return 0;
        else
            return new BigDecimal(temp)
                    .setScale(scale, BigDecimal.ROUND_HALF_UP)
                    .doubleValue();
    }

    public boolean getBoolean() {
        if (isValue())
            return _d.value.getBoolean();
        else
            return false;
    }

    public Date getDate() {
        if (isValue())
            return _d.value.getDate();
        else
            return null;
    }

    public char getChar() {
        if (isValue())
            return _d.value.getChar();
        else
            return 0;
    }

    public String getRawString() {
        if (isValue()) {
            return _d.value.getRawString();
        } else {
            return null;
        }
    }

    public Number getRawNumber() {
        if (isValue())
            return _d.value.getRawNumber();
        else
            return null;
    }

    public Boolean getRawBoolean() {
        if (isValue())
            return _d.value.getRawBoolean();
        else
            return null;
    }

    /**
     * 获取节点的值并以 rawDate 输出,果节点不是值类型,则输出null。
     * @return date
     */
    public Date getRawDate() {
        if (isValue())
            return _d.value.getRawDate();
        else
            return null;
    }

    ////////////////////
    //
    // 对象与数组公共处理
    //
    ////////////////////

    public void clear() {
        if (isObject()) {
            _d.object.clear();
        } else if (isArray()) {
            _d.array.clear();
        }
    }

    public int count() {
        if (isObject()) {
            return _d.object.size();
        }

        if (isArray()) {
            return _d.array.size();
        }

        return 0;
    }

    ////////////////////
    //
    // 对象处理
    //
    ////////////////////

    public Map obj() {
        return asObject()._d.object;
    }

    public boolean contains(String key) {
        if (isObject()) {
            return _d.object.containsKey(key);
        } else {
            return false;
        }
    }

    public JSONNode rename(String key, String newKey) {
        if (isObject()) {
            rename_do(this, key, newKey);
        } else if (isArray()) {
            for (JSONNode n : _d.array) {
                rename_do(n, key, newKey);
            }
        }

        return this;
    }

    private static void rename_do(JSONNode n,String key, String newKey) {
        if (n.isObject()) {
            JSONNode tmp = n._d.object.get(key);
            if (tmp != null) {
                n._d.object.put(newKey, tmp);
                n._d.object.remove(key);
            }
        }
    }

    public JSONNode get(String key) {
        _d.tryInitObject();

        JSONNode tmp = _d.object.get(key);
        if (tmp == null) {
            return new JSONNode(_o);
        } else {
            return tmp;
        }
    }

    public JSONNode getOrNew(String key) {
        _d.tryInitObject();

        JSONNode tmp = _d.object.get(key);
        if (tmp == null) {
            tmp = new JSONNode(_o);
            _d.object.put(key, tmp);
        }

        return tmp;
    }

    public JSONNode getOrNull(String key) {
        if(isObject()) {
            return _d.object.get(key);
        }else{
            return null;
        }
    }

    public JSONNode getNew(String key) {
        JSONNode tmp = new JSONNode(_o);
        _d.object.put(key, tmp);

        return tmp;
    }

    private JSONNode buildVal(Object val) {
        if (val instanceof Map) {
            return new JSONNode(_o).setAll((Map) val);
        } else if (val instanceof Collection) {
            return new JSONNode(_o).addAll((Collection) val);
        } else {
            //可能会影响性能...
            //
            if (val != null && val.getClass().isArray()) {
                return new JSONNode(_o).addAll(Arrays.asList((Object[]) val));
            }
            return new JSONNode(_o).val(val);
        }
    }

    /**
     * 设置对象的子节点(会自动处理类型)。
     *
     * @param key key
     * @param val 为常规类型或ONode
     * @return self:JSONNode
     */
    public JSONNode set(String key, Object val) {
        _d.tryInitObject();

        if (val instanceof JSONNode) {
            _d.object.put(key, ((JSONNode) val));
        } else {
            _d.object.put(key, buildVal(val));
        }

        return this;
    }

    /**
     * 设置对象的子节点,值为ONode类型 (需要在外部初始化类型)。
     * @param key key
     * @param val value
     * @return self:JSONNode
     */
    public JSONNode setNode(String key, JSONNode val) {
        _d.object.put(key, val);
        return this;
    }

    /**
     * 设置对象的子节点,将obj的子节点搬过来
     *
     * @param obj 对象类型的节点
     * @return self:JSONNode
     */
    public JSONNode setAll(JSONNode obj) {
        _d.tryInitObject();

        if (obj != null && obj.isObject()) {
            _d.object.putAll(obj._d.object);
        }

        return this;
    }

    public  JSONNode setAll(Map map) {
        _d.tryInitObject();

        if (map != null) {
            map.forEach((k, v) -> {
                set(k, v);
            });
        }
        return this;
    }

    public  JSONNode setAll(Map map, Act2 handler) {
        _d.tryInitObject();

        if (map != null) {
            map.forEach((k, v) -> {
                handler.run(this.get(k), v);
            });
        }
        return this;
    }

    public void remove(String key) {
        if(isObject()) {
            _d.object.remove(key);
        }
    }

    ////////////////////
    //
    // 数组处理
    //
    ////////////////////

    public List ary() {
        return asArray()._d.array;
    }

    public JSONNode get(int index) {
        _d.tryInitArray();
        if (index >= 0 && _d.array.size() > index) {
            return _d.array.get(index);
        }
        return new JSONNode(_o);
    }

    public JSONNode getOrNew(int index) {
        _d.tryInitArray();
        if (_d.array.size() > index) {
            return _d.array.get(index);
        } else {
            JSONNode n = null;
            for (int i = _d.array.size(); i <= index; i++) {
                n = new JSONNode(_o);
                _d.array.add(n);
            }
            return n;
        }
    }

    public JSONNode getOrNull(int index) {
        if(isArray()) {
            if (index >= 0 && _d.array.size() > index) {
                return _d.array.get(index);
            }
        }
        return null;
    }

    public void removeAt(int index) {
        if (isArray()) {
            _d.array.remove(index);
        }
    }

    public JSONNode addNew() {
        _d.tryInitArray();
        JSONNode n = new JSONNode(_o);
        _d.array.add(n);
        return n;
    }

    public JSONNode add(Object val) {
        _d.tryInitArray();

        if (val instanceof JSONNode) {
            _d.array.add((JSONNode) val);
        } else {
            _d.array.add(buildVal(val));
        }

        return this;
    }

    public JSONNode addNode(JSONNode val) {
        _d.array.add(val);
        return this;
    }

    public JSONNode addAll(JSONNode ary) {
        _d.tryInitArray();

        if (ary != null && ary.isArray()) {
            _d.array.addAll(ary._d.array);
        }

        return this;
    }

    /**
     * 添加数组子节点,将ary的成员点搬过来。
     *
     * @param  type
     * @param ary ary
     * @return self:JSONNode
     */
    public  JSONNode addAll(Collection ary) {
        _d.tryInitArray();

        if (ary != null) {
            ary.forEach(m -> add(m));
        }
        return this;
    }

    /**
     * 添加数组子节点,将ary的成员点搬过来,并交由代理处置。
     * @param  type
     * @param ary list
     * @param handler handler
     * @return self:JSONNode
     */
    public  JSONNode addAll(Collection ary, Act2 handler) {
        _d.tryInitArray();

        if (ary != null) {
            ary.forEach(m -> handler.run(addNew(), m));
        }
        return this;
    }

    //////////////////////

    public boolean isNull() {
        return (_d.nodeType == JSONNodeType.Null) || (isValue() && _d.value.isNull());
    }

    public boolean isValue() {
        return _d.nodeType == JSONNodeType.Value;
    }

    public boolean isObject() {
        return _d.nodeType == JSONNodeType.Object;
    }

    public boolean isArray() {
        return _d.nodeType == JSONNodeType.Array;
    }

    //////////////////////

    public JSONNode forEach(BiConsumer consumer) {
        if (isObject()) {
            _d.object.forEach(consumer);
        }

        return this;
    }

    public JSONNode forEach(Consumer consumer) {
        if (isArray()) {
            _d.array.forEach(consumer);
        }

        return this;
    }

    ////////////////////
    //
    // 特性处理
    //
    ////////////////////

    public String attrGet(String key) {
        return _d.attrGet(key);
    }

    public JSONNode attrSet(String key, String val) {
        _d.attrSet(key, val);
        return this;
    }

    public JSONNode attrForeach(BiConsumer consumer) {
        if (_d.attrs != null) {
            _d.attrs.forEach(consumer);
        }
        return this;
    }

    ////////////////////
    //
    // 转换操作
    //
    ////////////////////

    @Override
    public String toString() {
        return to(JSONDefaultConstants.DEF_STRING_TOER);
    }

    public String toJson() {
        return to(JSONDefaultConstants.DEF_JSON_TOER);
    }

    public Object toData() {
        return to(JSONDefaultConstants.DEF_OBJECT_TOER);
    }

    public  T toObject(Type clz) {
        return to(JSONDefaultConstants.DEF_OBJECT_TOER, clz);
    }

    public List toObjectList(Class clz){
        List list = new ArrayList<>();
        for(JSONNode n: ary()){
            list.add(n.toObject(clz));
        }
        return list;
    }

    @Deprecated
    public List toArray(Class clz){
        return toObjectList(clz);
    }

    /**
     * 将当前ONode 通过 toer 进行转换。
     * @param  type
     * @param toer ToHandler
     * @param clz Type
     * @return 对象
     */
    public  T to(ToHandler toer, Type clz) {
        return (T) (new JSONContext(_o, this, clz).handle(toer).target);
    }
    public  T to(ToHandler toer) {
        return to(toer, null);
    }


    /**
     * 填充数据(如有问题会跳过,不会出异常)
     *
     * @param source 可以是 String 或 java object 数据
     * @return self:JSONNode
     */
    public JSONNode fill(Object source) {
        val(doLoad(source, source instanceof String, _o, null));
        return this;
    }

    public JSONNode fill(Object source,  Feature... features) {
        val(doLoad(source, source instanceof String, JSONOptions.def().add(features), null));
        return this;
    }

    public JSONNode fillObj(Object source, Feature... features) {
        val(doLoad(source, false, JSONOptions.def().add(features), null));
        return this;
    }

    public JSONNode fillStr(String source, Feature... features) {
        val(doLoad(source, true, JSONOptions.def().add(features), null));
        return this;
    }

    ////////////////////
    //
    // 来源加载
    //
    ////////////////////

    /**
     * 加载数据并生成新节点(如果异常,会生成空ONode)
     *
     * @param source 可以是 String 或 java object 数据
     * @return new:JSONNode
     */
    public static JSONNode load(Object source) {
        return load(source, null, null);
    }

    public static JSONNode load(Object source, Feature... features) {
        return load(source, JSONOptions.def().add(features), null);
    }

    public static JSONNode load(Object source, JSONOptions opts) {
        return load(source, opts, null);
    }

    public static JSONNode load(Object source, JSONOptions opts, FromHandler fromer) {
        return doLoad(source, source instanceof String, opts, fromer);
    }

    public static JSONNode loadStr(String source) {
        return doLoad(source, true, null, null);
    }

    public static JSONNode loadStr(String source, JSONOptions opts) {
        return doLoad(source, true, opts, null);
    }

    public static JSONNode loadStr(String source, Feature... features) {
        return doLoad(source, true, JSONOptions.def().add(features), null);
    }

    public static JSONNode loadObj(Object source) {
        return doLoad(source, false, null, null);
    }

    //loadStr 不需要 opts
    public static JSONNode loadObj(Object source, JSONOptions opts) {
        return doLoad(source, false, opts, null);
    }

    public static JSONNode loadObj(Object source, Feature... features) {
        return doLoad(source, false, JSONOptions.def().add(features), null);
    }

    private static JSONNode doLoad(Object source, boolean isString, JSONOptions opts, FromHandler fromer) {
        if (fromer == null) {
            if (isString) {
                fromer = JSONDefaultConstants.DEF_STRING_FROMER;
            } else {
                fromer = JSONDefaultConstants.DEF_OBJECT_FROMER;
            }
        }

        if (opts == null) {
            opts = JSONOptions.def();
        }

        return (JSONNode) new JSONContext(opts, source).handle(fromer).target;
    }

    ////////////////////
    //
    // 字符串化
    //
    ////////////////////

    public static String stringify(Object source) {
        return stringify(source, JSONOptions.def());
    }

    public static String stringify(Object source, Feature... features) {
        if (features.length > 0) {
            return stringify(source, new JSONOptions(Feature.of(features)));
        } else {
            return stringify(source, JSONOptions.def());
        }
    }

    public static String stringify(Object source, JSONOptions opts) {
        //加载java object,须指定Fromer
        return load(source, opts, JSONDefaultConstants.DEF_OBJECT_FROMER).toString();
    }

    ////////////////////
    //
    // 序列化
    //
    ////////////////////

    public static String serialize(Object source) {
        //加载java object,须指定Fromer
        return load(source, JSONOptions.serialize(), JSONDefaultConstants.DEF_OBJECT_FROMER).toJson();
    }

    public static  T deserialize(String source) {
        return deserialize(source, Object.class);
    }

    public static  T deserialize(String source, Type clz) {
        //加载String,不需指定Fromer
        return load(source,  JSONOptions.serialize(), null).toObject(clz);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (o == null) {
            return isNull();
        }

        if(isArray()) {
            if (o instanceof JSONNode) {
                return Objects.equals(ary(), ((JSONNode) o).ary());
            } else {
                return Objects.equals(ary(), o);
            }
        }

        if(isObject()) {
            if (o instanceof JSONNode) {
                return Objects.equals(obj(), ((JSONNode) o).obj());
            } else {
                return Objects.equals(obj(), o);
            }
        }

        if(isValue()){
            if (o instanceof JSONNode) {
                return Objects.equals(val(), ((JSONNode) o).val());
            } else {
                return Objects.equals(val(), o);
            }
        }

        /*最后是null type*/
        if(o instanceof JSONNode){
            /*都是 null*/
            return ((JSONNode) o).isNull();
        }else{
            return false;
        }
    }

    @Override
    public int hashCode() {
        return _d.hashCode();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy