我是 GSON 的新手。我有一个 JSON 对象(作为字符串)-
{
"name" : "myName",
"city" : "myCity"
}
我解析如下 -
JsonParser parser = new JsonParser();
JsonObject json_result = (JsonObject)parser.parse(#TheAboveMentionedStringGoesHere);
现在我想用其他东西替换键 name
,比如 firstName
这样生成的 JSON 对象是 -
{
"firstName" : "myName",
"city" : "myCity"
}
这可能吗?我如何实现这一点?
最佳答案
如果你使用com.google.code.gson:gson:2.+
Google 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和Deserializer,请阅读this documention .
希望对您有所帮助。
关于json - 替换 GSON 中的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29469788/