gpt4 book ai didi

java - GSON java 我怎样才能在映射和打印之间使用不同的名称?

转载 作者:太空狗 更新时间:2023-10-29 14:47:29 27 4
gpt4 key购买 nike

我有一个这样的 JSON:

{
"aggregation": {
"CityAgg" : {
"key" : "Paris"
}
}
}

我创建映射并为每个字段添加一个 @SerializedName 因为我想为我的变量创建自定义名称。

例如在 JSON 中,有一个键名 key,但我希望我在 Java 中的变量是 cityName

所以,我这样做:

@SerializedName("key")
public String cityName

我可以像这样动态地将响应 JSON 映射到我的对象:

Gson gson = new Gson();
Query2 query2 = gson.fromJson(response, Query2.class);

它运行良好。

但是,当我想打印映射对象时,我会这样做:

String query2String = gson.toJson(query2);
Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gsonPretty.toJson(query2String);

问题是,在 prettyJson 中,我可以看到 key,而不是 cityName

我想知道是否有办法自定义它。我不想看到 key

最佳答案

如果您不想将自定义序列化器/反序列化器类编写为 Viswanath Lekshmanan已经提到,您始终可以创建某种 DTO 对象。

您的域类:

class CityAgg {
@SerializedName("key")
protected String cityName;

public String getCityName() {
return cityName;
}
}

class Aggregation {
@SerializedName("CityAgg")
protected CityAgg cityAgg;

public CityAgg getCityAgg() {
return cityAgg;
}
}

class Query2 {
@SerializedName("aggregation")
protected Aggregation aggregation;

public Aggregation getAggregation() {
return aggregation;
}
}

示例 DTO 类:

class CityAggDto {
protected String cityName;

public CityAggDto(CityAgg query2) {
this.cityName = query2.getCityName();
}
}

示例使用:

String response = "{ \"aggregation\": { \"CityAgg\": { \"key\": \"value\" } } }";

Gson gson = new Gson();
Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();

Query2 query2 = gson.fromJson(response, Query2.class);
CityAggDto cityAggDto = new CityAggDto(query2.getAggregation().getCityAgg());

String cityAggDtoJson = gson.toJson(cityAggDto);
String cityAggDtoPrettyJson = gsonPretty.toJson(cityAggDto);

Log.d(TAG, "onCreate: " + cityAggDtoJson);
Log.d(TAG, "onCreate: " + cityAggDtoPrettyJson);

结果:

enter image description here

@SerializationName 注释用于序列化和反序列化这两个操作 - 这就是为什么您的 JSON 字符串包含 key 键。

令人遗憾的是,尽管 @SerializationName 注释可以与方法一起使用 - 对 getter 和 setter 使用不同的值将不起作用,因为 GSON 仅基于字段:

Using fields vs getters to indicate Json elements

Some Json libraries use the getters of a type to deduce the Json elements. We chose to use all fields (up the inheritance hierarchy) that are not transient, static, or synthetic. We did this because not all classes are written with suitably named getters. Moreover, getXXX or isXXX might be semantic rather than indicating properties.

However, there are good arguments to support properties as well. We intend to enhance Gson in a latter version to support properties as an alternate mapping for indicating Json fields. For now, Gson is fields-based.

来源:https://github.com/google/gson/blob/master/GsonDesignDocument.md

这就是我转向 Jackson 的原因。 :)

关于java - GSON java 我怎样才能在映射和打印之间使用不同的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38327636/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com