替换GSON中的密钥 [英] Replace a key in GSON
问题描述
我是GSON的新手.我有一个JSON对象(作为字符串)-
I'm new to GSON. I have a JSON object (As a String) -
{
"name" : "myName",
"city" : "myCity"
}
我将其解析如下-
JsonParser parser = new JsonParser();
JsonObject json_result = (JsonObject)parser.parse(#TheAboveMentionedStringGoesHere);
现在,我想将键name
替换为其他内容,例如firstName
,以使生成的JSON对象为-
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?
推荐答案
如果您使用com.google.code.gson:gson:2.+
Google GSON第三方库,然后根据其.
因此,您的模型类可能如下所示:
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);
最后,如果您认为需要使用自定义的Serialiazer和Deserializer,请阅读
at last if you think you need to use customized Serialiazer and Deserializer, please read this documention.
I hope this helps you.
这篇关于替换GSON中的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!