问题
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