2015-04-06 82 views
0

我是GSON的新手。我有一個JSON對象(字符串) -替換GSON中的密鑰

{ 
"name" : "myName", 
"city" : "myCity" 
} 

我解析這個如下 -

JsonParser parser = new JsonParser(); 
JsonObject json_result = (JsonObject)parser.parse(#TheAboveMentionedStringGoesHere); 

現在我想更換關鍵name別的東西,比如說,firstName使得所得到的JSON對象是 -

{ 
"firstName" : "myName", 
"city" : "myCity" 
} 

這可能嗎?我如何實現這一目標?

回答

0

,你可以這樣做:那麼先添加刪除

json_result.add("firstName", json_result.get("name")); 

     json_result.remove("name"); 
0
JsonParser parser = new JsonParser(); 
JsonObject json_result = (JsonObject)parser.parse(#TheAboveMentionedStringGoesHere); 

有一個構造函數的JSONObject作爲參數,但名字爲它的字段名其他類似的對象。

public class json2{ 
    String firstname; 
    String city; 
    public json2(JsonObject){ 
     this.firstname=JsonObject.name; 
     this.city=JsonObject.city; 
    } 

} 

json2 j = new json2(JsonObject); 
String jsonString = Gson.toJson(j); 

你會得到你想要

0

下面的函數將通過一個對象及其所有子對象/數組的搜索什麼,並替換爲新價值的關鍵。這將在全球範圍適用,因此第一次更換後也不會停止

function findAndReplace(object, value, replacevalue){ 
    for(var x in object){ 
if(typeof object[x] == 'object'){ 
    findAndReplace(object[x], value, replacevalue); 
} 
if(object[x] == value){ 
    object["name"] = replacevalue; 
    // break; 
} 
} 
} 

請查看以下鏈接

JS

1

如果你使用谷歌com.google.code.gson:gson:2.+ GSON第三方庫,然後根據它是documentations,您可以在模型類或POJO中使用@SerializedName("commits_url")。 所以你的模型類可能是象下面這樣:

public class Example { 

    @SerializedName("first_name") 
    String name; 

    @SerializedName("city") 
    String city; 
} 

而且當你要使用它:

Gist gist = new Gson().fromJson("{ 
"firstName" : "myName", 
"city" : "myCity" 
}", Gist.class); 

最後,如果你認爲你需要使用定製Serialiazer器和解串器,請閱讀this documention
我希望這可以幫助你。