-
Notifications
You must be signed in to change notification settings - Fork 61
Description
Hi all,
Issue Summary
When using hx-vals instead of hidden input fields for address lookup data from OpenStreetMap, null values are handled differently.
Current Behavior
Hidden inputs: Empty properties are serialized as empty strings ("")
hx-vals: Empty properties are serialized as null in the JSON output, which is expected given that null is a valid value in JSON. Thymeleaf prints out 'null' in the UI.
Example Use Case
I'm building an address lookup component using OpenStreetMap data. Some addresses have optional fields (like building names) that may be null. While this worked fine with hidden inputs, switching to hx-vals caused 'null' being printed in the UI.
Current Workaround
Given that HtmxThymeleafAutoConfiguration uses a standard JsonMapper, I've implemented a custom HtmxDialect configuration that forces null values to be serialized as empty strings:
@Configuration
public class HtmxDialectConfig {
@Bean
@Primary
public HtmxDialect customHtmxDialect() {
JsonSerializer<Object> nullSerializer =
new JsonSerializer<>() {
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
gen.writeString("");
}
};
JsonMapper jsonMapper = JsonMapper.builder().build();
jsonMapper.getSerializerProvider().setNullValueSerializer(nullSerializer);
return new HtmxDialect(jsonMapper);
}
}Questions
- Are there potential side effects to serializing null values as empty strings in HtmxDialect?
- If hx-vals is meant to replace hidden inputs, should it handle null values consistently with hidden inputs?
- Is there a better approach to handling optional fields in this context?
When working with external APIs like OpenStreetMap, null values are common for optional fields. While we could handle null checks explicitly, it would be more convenient if hx-vals behaved consistently with hidden inputs.
Thank you.
