gpt4 book ai didi

json - 具有枚举键的 Map 的 GSON 自定义序列化器

转载 作者:行者123 更新时间:2023-12-02 14:50:33 32 4
gpt4 key购买 nike

我正在序列化的对象包含一个映射,其中的键是枚举。这些枚举有一个变量。当我使用 GSON 序列化它时,我希望生成的 JSON 具有 Enum 变量而不是默认的 Enum 名称。我尝试创建自定义序列化器并注册它,但它没有成功。这是我的代码。

Controller :

@Controller
public class CheckoutClientController {

@Autowired
private Gson gson;
@Autowired
private RequestHelper requestHelper;
@Autowired
private SettingsReader settingsReader;

@InitBinder
public void initBinder(final WebDataBinder binder) {
binder.registerCustomEditor(CheckoutConfigurationDto.class, new JsonDeserializerPropertyEditor<CheckoutConfigurationDto>(gson, CheckoutConfigurationDto.class));
}

/**
* Handles requests to the Checkout Client page, which is the outer wrapper that includes the white label checkout (WLC) iframe. Sets up the configuration
* data needed to pass to the WLC server.
*
* @return the model and view
*/
@RequestMapping(value = "/checkout/checkout-client.ep", method = RequestMethod.GET)
public ModelAndView showPage(HttpServletRequest request) {
CheckoutClientConfigurationDto checkoutClientConfig = new CheckoutClientConfigurationDto();

StringBuilder host = new StringBuilder();
host.append(request.getScheme()).append("://");
host.append(request.getServerName());
host.append(":").append(request.getServerPort());

checkoutClientConfig.setWlcHost(host.toString());
checkoutClientConfig.setClientId("clientId");
checkoutClientConfig.setAppId("appId");
checkoutClientConfig.setId("wlc-widget");

Map<CheckoutClientConfigurationOption, Boolean> options = checkoutClientConfig.getOptions();

options.put(CheckoutClientConfigurationOption.SHOW_ORDER_CONFIRMATION,
Boolean.valueOf(this.settingsReader.getSettingValue(SettingsConstants.SHOW_ORDER_CONFIRMATION).getValue()));
options.put(CheckoutClientConfigurationOption.REMOVE_CART_ITEMS,
Boolean.valueOf(this.settingsReader.getSettingValue(SettingsConstants.REMOVE_CART_ITEMS).getValue()));

return new ModelAndView(ViewConstants.CHECKOUT_CLIENT_TEMPLATE_PATH, "checkoutClientConfig", gson.toJson(checkoutClientConfig));
}
}

CheckoutClientConfigurationDto(减去所有样板 getter/setter):

public class CheckoutClientConfigurationDto implements Dto {

private String wlcHost;

private String clientId;

private String appId;

private String id;

private Map<CheckoutClientConfigurationOption, Boolean> options;

public CheckoutClientConfigurationDto() {
products = new ArrayList<ProductDto>();
options = new HashMap<CheckoutClientConfigurationOption, Boolean>();
}

public Map<CheckoutClientConfigurationOption, Boolean> getOptions() {
return options;
}

public void setOptions(final Map<CheckoutClientConfigurationOption, Boolean> options) {
this.options = options;
}
}

CheckoutClientConfigurationOption:

public enum CheckoutClientConfigurationOption {

SHOW_SAVED_ADDRESSES("showSavedAddresses", true),
SHOW_CART_SUMMARY("showCartSummary", true),
REMOVE_CART_ITEMS("removeCartItems", true),
SHOW_DISCOUNT_FIELD("showDiscountField", true),
SHOW_VAT_CODE("showVatCode", true),
SHOW_ORDER_CONFIRMATION("showOrderConfirmation", true),
SHOW_CANCEL_BUTTON("showCancelButton", false),
SINGLE_PAGE_CHECKOUT("singlePageCheckout", false),
SEND_ORDER_CONFIRMATION_EMAIL("sendOrderConfirmationEmail", true),
SEND_SHIPPING_CONFIRMATION_EMAIL("sendShippingConfirmationEmail", true);

private String optionName;

private boolean defaultValue;

private CheckoutClientConfigurationOption(final String optionName, final boolean defaultValue) {
this.optionName = optionName;
this.defaultValue = defaultValue;
}

public boolean getDefautValue() {
return defaultValue;
}

public String getOptionName() {
return optionName;
}
}

我的自定义 GSON 序列化器:

public class CheckoutClientConfigurationOptionGsonSerializer implements JsonSerializer<CheckoutClientConfigurationOption> {

@Override
public JsonElement serialize(CheckoutClientConfigurationOption src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getOptionName());
}

}

我的自定义 GSON 配置器:

public class GsonConfigurer {

private Map<Class<?>, Object> typeAdapterMap;

public Gson create() {
final GsonBuilder gsonBuilder = new GsonBuilder();

for (final Entry<Class<?>, Object> typeAdapterMapping : typeAdapterMap.entrySet()) {
gsonBuilder.registerTypeAdapter(typeAdapterMapping.getKey(), typeAdapterMapping.getValue());
}

return gsonBuilder.create();
}

protected Map<Class<?>, Object> getTypeAdapterMap() {
return typeAdapterMap;
}

public void setTypeAdapterMap(final Map<Class<?>, Object> typeAdapterMap) {
this.typeAdapterMap = typeAdapterMap;
}

}

XML:

<bean id="gsonConfigurer" class="com.sfweb.gson.GsonConfigurer">
<property name="typeAdapterMap">
<util:map key-type="java.lang.Class">
<entry key="com.sfweb.dto.CheckoutConfigurationOption">
<bean class="com.sfweb.dto.deserializer.CheckoutConfigurationOptionGsonDeserializer" />
</entry>
<entry key="com.sfweb.dto.CheckoutClientConfigurationOption">
<bean class="com.sfweb.dto.serializer.CheckoutClientConfigurationOptionGsonSerializer" />
</entry>
</util:map>
</property>
</bean>

<bean class="com.google.gson.Gson" factory-bean="gsonConfigurer" factory-method="create" />

我还有一个自定义反序列化器,正如您在 XML 中看到的那样。那个工作没有问题。我在 Debug模式下运行,并且 CheckoutClientConfigurationOptionGsonSerializer 中的行从未被命中。我检查了我调用 toJson() 的 gson 对象中是否有自定义序列化器。所以我不确定问题是什么。我有一种感觉,我只是缺少一件。

我希望生成的 JSON 显示“showSavedAddresses”,但它却显示“SHOW_SAVED_ADDRESSES”。预先感谢您的帮助!

最佳答案

阅读 GsonBuilder#enableComplexMapKeySerialization 上的文档我看到这个:

The default implementation of map serialization uses toString() on the key

因此,默认情况下它不会在 map 键上运行您的 TypeAdapter。我尝试简单地调用此方法并让我的枚举显示为数字字符串。

关于json - 具有枚举键的 Map 的 GSON 自定义序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9844920/

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