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<String> 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分支

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,523评论 19 139
  • JSON JSON和XML都是需要解析的 JSON是一种轻量级的数据格式,一般用于数据交互服务器返回给客户端的数据...
    JonesCxy阅读 5,876评论 2 10
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,226评论 4 61
  • 六月七号八号结束了,高三的学生面临着毕业,可毕业对他们来说意味着什么呢? 在有些家庭,条件比较好,他...
    夏花寒枝阅读 2,839评论 0 2
  • 慧语禅心:砍柴担水做饭 行者问老和尚:“您得道前,做什么?”老和尚说:“砍柴担水做饭。”行者问:“那得道后呢?”老...
    xcy无名阅读 3,940评论 0 0