如何维护 JSONObject 的顺序

Jol*_*oly 9 java json

我正在使用JSONObject来删除我在 JSON 字符串中不需要的 certin 属性:

JSONObject jsonObject = new JSONObject(jsonString);
jsonObject.remove("owner");
jsonString = jsonObject.toString();
Run Code Online (Sandbox Code Playgroud)

它工作正常,但问题是 JSONObject 是“名称/值对的无序集合”,我想保持 String 在通过 JSONObject 操作之前的原始顺序。

知道如何做到这一点吗?

any*_*oby 5

我最近遇到了同样的问题,只是将我们所有的测试(期望 JSON 属性的顺序相同)转换到另一个 JSON 库:

<dependency>
    <groupId>org.codehaus.jettison</groupId>
    <artifactId>jettison</artifactId>
    <version>1.3.5</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

它在内部使用 a LinkedHashMap,它维护属性的顺序。这个库在功能上等同于这个json.org库,所以我看不出有什么理由不使用它,至少在测试中是这样。


Ami*_*ain 5

您可以使用 com.google.gson 提供的 JsonObject,它与 org.json 提供的 JSONObject 几乎相同,但功能有所不同。为了将 String 转换为 Json 对象并保持顺序,您可以使用:

Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(<Json String>, JsonObject.class);
Run Code Online (Sandbox Code Playgroud)

例如:-

String jsonString = "your json String";

JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
Run Code Online (Sandbox Code Playgroud)

它只是维护 JsonObject 与 String 的顺序。


tre*_*us7 5

尝试这个

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();
Run Code Online (Sandbox Code Playgroud)

  • @David 你的建议没有涵盖 JSONObject 的所有 3 个构造函数。带map参数的构造函数的问题在于,在字段map未填充之前,无法将其更改为LinkedHashMap (2认同)

bri*_*ice 2

你不能。

这就是为什么我们将其称为名称/值对的无序集合

我不确定为什么你需要这样做。但如果你想排序,你就必须使用 json 数组。

  • 我只需要它,很难在这里解释整个系统:) JSON 数组似乎是正确的方法,谢谢 (2认同)