Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain the order of a JSONObject

Tags:

java

json

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.remove("owner");
jsonString = jsonObject.toString();

It works ok however the problem is that the JSONObject is "an unordered collection of name/value pairs" and I want to maintain the original order the String had before it went through the JSONObject manipulation.

Any idea how to do this?

like image 895
Joly Avatar asked Mar 28 '12 13:03

Joly


2 Answers

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();
like image 116
tremendous7 Avatar answered Oct 16 '22 08:10

tremendous7


You can go for the JsonObject provided by the com.google.gson it is nearly the same with the JSONObject by org.json but some different functions. For converting String to Json object and also maintains the order you can use:

Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(<Json String>, JsonObject.class);

For eg:-

String jsonString = "your json String";

JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);

It just maintains the order of the JsonObject from the String.

like image 27
Amit Jain Avatar answered Oct 16 '22 08:10

Amit Jain