Replace a key in GSON

丶灬走出姿态 提交于 2020-01-05 08:10:43

问题


I'm new to GSON. I have a JSON object (As a String) -

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

I parsed this as follows -

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

Now I want to replace the key name with something else ,say, firstName so that the resulting JSON object is -

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

Is this possible? How do I achieve this?


回答1:


If you use com.google.code.gson:gson:2.+ Google GSON third party library, and then according to it's documentations, you can use @SerializedName("commits_url")in the model class or POJO. So your model class might be like below :

public class Example {

    @SerializedName("first_name")
    String name;

    @SerializedName("city")
    String city;
}

and also when you want use it as :

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

at last if you think you need to use customized Serialiazer and Deserializer, please read this documention.
I hope this helps you.




回答2:


you can do this : first add then remove

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

        json_result.remove("name");



回答3:


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

have another similar object with a constructor that takes JsonObject as its parameter, but has firstname as its field name.

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);

You will get what you want




回答4:


The following function will search through an object and all of its child objects/arrays, and replace the key with the new value. It will apply globally, so it won't stop after the first replacement

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; 
 }
}
}

Please check the Below Link

JS



来源:https://stackoverflow.com/questions/29469788/replace-a-key-in-gson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!