JAVA—JSON 有序参数和增强的类型方法

有时候json的key值顺序对于业务来说是有意义的,而且java-json的类型判断使用起来很困难。

根据定义json的key是无序集合,但是hash code顺序处理的感觉有点随意。如果你注意浏览器的实现,chrome浏览器是可以记录key顺序的。原生的opt**方法是试图转换成某种类型,但是几乎任何事物都可以转换成string,所以判断JOSNObject中键值的类型需要一些技巧,例如注意顺序,其实增加类似typeof的方法就可以有更加精确的值类型信息。

我给官方的实现提了request,但是没有被接受。

  • 以下是我的简单实现 :

JSONObjectKeyOrder

package org.json;

import java.util.ArrayList;
import java.util.List;

/**
 * sometimes we need key order in input,hashmap`s keyset is chaos.
 * @author wangq
 *
 */
public class JSONObjectKeyOrder extends JSONObject {
    // store the name in order
    private List names;
    
    public JSONObjectKeyOrder(String source) throws JSONException {

        this(new JSONTokenerKeyOrder(source));
    }

    public JSONObjectKeyOrder(JSONTokenerKeyOrder jsonTokenerKeyOrder) {
        super(jsonTokenerKeyOrder);

    }

    public JSONObjectKeyOrder putOnce(String key, Object value) throws JSONException {
        super.putOnce(key, value);
        if (names == null) {
            names = new ArrayList<>();
        }
        names.add(key);
        return this;
    }
    /**
     * null is ugly,and evil
     * @param jo
     * @return
     */
    public static String[] getNames(JSONObjectKeyOrder jo) {
        if (jo.names == null) {
            return new String[0];
        }
        return jo.names.toArray(new String[0]);
    }
    /**
     * i do`t like the opt** methods,it`s hard to get type,such the everything can be cast to String
     * 
     * @param key
     * @return
     */
    public boolean isInt(String key) {
        try {
            Integer.parseInt(optString(key));
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

JSONTokenerKeyOrder


package org.json;

public class JSONTokenerKeyOrder extends JSONTokener{

    public JSONTokenerKeyOrder(String s) {
        super(s);
    }
    /**
     * 
     */
    public Object nextValue() throws JSONException {
        char c = this.nextClean();
        String string;

        switch (c) {
            case '"':
            case '\'':
                return this.nextString(c);
            case '{':
                this.back();
                return new JSONObjectKeyOrder(this);
            case '[':
                this.back();
                return new JSONArray(this);
        }

        /*
         * Handle unquoted text. This could be the values true, false, or
         * null, or it can be a number. An implementation (such as this one)
         * is allowed to also accept non-standard forms.
         *
         * Accumulate characters until we reach the end of the text or a
         * formatting character.
         */

        StringBuilder sb = new StringBuilder();
        while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
            sb.append(c);
            c = this.next();
        }
        this.back();

        string = sb.toString().trim();
        if ("".equals(string)) {
            throw this.syntaxError("Missing value");
        }
        return JSONObject.stringToValue(string);
    }
}

TestMain


package org.json;
/**
 * test JSONObjectKeyOrder
 * @author wangq
 *
 */
public class TestMain {
public static void main(String[] args) {
    JSONObject jsonObject = new JSONObject("{a:1,d:{z:2,a:2},b:3}");
    System.out.println(jsonObject);
    
    JSONObjectKeyOrder jsonObject1 = new JSONObjectKeyOrder("{a:1,d:{z:2,a:2},b:3}");
    print(jsonObject1,"");
}

/**
 *a
 *d
 *  z
 *  a
 *b
 * @param jsonObject
 * @param index
 */
static void print(JSONObjectKeyOrder jsonObject,String index){
    String[] names = JSONObjectKeyOrder.getNames(jsonObject);
    for (String string : names) {
        System.out.println(index+string);
        if(jsonObject.optJSONObject(string)!=null){
            print((JSONObjectKeyOrder) jsonObject.optJSONObject(string),index+"  ");
        }
        
    }
}
}


欢迎访问我的git分支

你可能感兴趣的:(JAVA—JSON 有序参数和增强的类型方法)