簡體   English   中英

將值添加到 Java 中的 JSONObject

[英]Prepend value to a JSONObject in Java

有沒有一種可能的方法來為 Java 中的 JSONObject 添加一個值?

例如,我有一個 JSONObject 說:

{
    "one" : 1,
    "two" : 2,
    "three" : 3,
    "four" : 4,
    "five" : 5
}

現在我想為其添加另一個值,但如果我說:

jsonObject.put("zero", 0);

我會有這樣的事情:

{
    "one" : 1,
    "two" : 2,
    "three" : 3,
    "four" : 4,
    "five" : 5,
    "zero" : 0
}

但是有沒有辦法我可以預先添加一個新值,比如jsonObject.prepend("zero", 0); 所以我會有

{
    "zero" : 0,
    "one" : 1,
    "two" : 2,
    "three" : 3,
    "four" : 4,
    "five" : 5
}

注意:我有一個隨機密鑰,只是以這個為例。 我什至不知道密鑰,我從數據庫中提取它們,所以我不可能對密鑰進行排序

好吧...我必須想辦法解決這個問題。 它看起來有點臟,但效果很好。

我必須創建自己的JsonObject class 擴展JSONObject到它,然后添加一個前置方法

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

public class JsonObject extends JSONObject {

    //create method to prepend object
    public JsonObject prepend(String key, Object object) throws JSONException {
        JSONArray keysArray = this.names();  //save the object keys
        JSONArray objArray = new JSONArray();
        Iterator iterator = this.keys();
        while (iterator.hasNext()){
            String k = (String) iterator.next();
            objArray.put(this.get(k));   //save the object
        }
        this.removeAll();    // empty the JsonObject
        this.put(key, object);    // now it's empty, put the new object, making it to be the 1st(prepending trick)
        assert keysArray != null;
        if(keysArray.length() > 0) {
            for(int i = 0; i < keysArray.length(); i++) {
                String exKey = keysArray.getString(i);
                assert objArray != null;
                Object o = objArray.get(i);
                if(!key.equals(exKey))
                    this.put(exKey, o);    // put back the saved keys and object
            }
        }
        return this;
    }

    // method to empty the JsonObject
    public void removeAll() throws JSONException {
        JSONArray array = this.names();
        assert array != null;
        if(array.length() > 0) {
            for(int i = 0; i < array.length(); i++) {
                String key = array.getString(i);
                this.remove(key);
            }
        }
    }

}

然后在我的代碼中使用它

JsonObject object = new JsonObject();
object.put("one", 1);
object.put("two", 2);
object.put("three", 3);
object.put("four", 4);
object.put("five", 5); 
object.prepend("zero", 0);
Log.i("object" object.toString());

結果

{
    "zero" : 0,
    "one" : 1,
    "two" : 2,
    "three" : 3,
    "four" : 4,
    "five" : 5
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM