json - 替换 GSON 中的 key

标签 json gson

我是 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/

相关文章:

javascript - 如何在 JavaScript 中将对象数组转换为简单数组?

java - Gson toJson 方法在打印字符串时包含转义字符

java - 使用 GSON 和 TypeAdapter 将 BSON (mongoDB) 读入 POJO

json - 向 JSON 文件添加注释

json - 如何使用 postman 发布对象和列表

java - NoClassDefFoundError : org/json/JSONArray

c# - JSON.NET:如何在不在数组中的情况下仅序列化 DataTable 对象中的一行?

java - com.google.gson.JsonSyntaxException : java. lang.IllegalStateException:应为 BEGIN_OBJECT 但在第 2 行第 5 列为 STRING

java - 如何发布使用 GSON 解析大型 json 文件的进度

java - 使用 gson 从对象列表中获取 JSON 字符串