How to maintain the order of a JSONObject

后端 未结 12 1613
栀梦
栀梦 2020-12-11 05:49

I am using a JSONObject in order to remove a certin attribute I don\'t need in a JSON String:

JSONObject jsonObject = new JSONObject(jsonString);
jsonObject.         


        
12条回答
  •  轮回少年
    2020-12-11 06:35

    try this

    JSONObject jsonObject = new JSONObject(jsonString) {
        /**
         * changes the value of JSONObject.map to a LinkedHashMap in order to maintain
         * order of keys.
         */
        @Override
        public JSONObject put(String key, Object value) throws JSONException {
            try {
                Field map = JSONObject.class.getDeclaredField("map");
                map.setAccessible(true);
                Object mapValue = map.get(this);
                if (!(mapValue instanceof LinkedHashMap)) {
                    map.set(this, new LinkedHashMap<>());
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            return super.put(key, value);
        }
    };
    jsonObject.remove("owner");
    jsonString=jsonObject.toString();
    

提交回复
热议问题