|
19 | 19 | import com.fasterxml.jackson.annotation.JsonInclude; |
20 | 20 | import com.fasterxml.jackson.core.JsonProcessingException; |
21 | 21 | import com.fasterxml.jackson.databind.ObjectMapper; |
22 | | -import com.fasterxml.jackson.databind.PropertyNamingStrategies; |
23 | 22 |
|
24 | 23 | class JacksonSerializer implements Serializer { |
25 | 24 |
|
26 | | - private ObjectMapper mapper = |
27 | | - new ObjectMapper().setPropertyNamingStrategy( |
28 | | - PropertyNamingStrategies.SNAKE_CASE); |
| 25 | + private ObjectMapper mapper = createMapper(); |
| 26 | + |
| 27 | + /** |
| 28 | + * Creates an ObjectMapper with snake_case naming strategy. |
| 29 | + * Supports both Jackson 2.12+ (PropertyNamingStrategies) and earlier versions (PropertyNamingStrategy). |
| 30 | + * Uses reflection to avoid compile-time dependencies on either API. |
| 31 | + */ |
| 32 | + static ObjectMapper createMapper() { |
| 33 | + ObjectMapper objectMapper = new ObjectMapper(); |
| 34 | + Object namingStrategy = getSnakeCaseStrategy(); |
| 35 | + |
| 36 | + try { |
| 37 | + // Use setPropertyNamingStrategy method (available in all versions) |
| 38 | + objectMapper.getClass() |
| 39 | + .getMethod("setPropertyNamingStrategy", |
| 40 | + Class.forName("com.fasterxml.jackson.databind.PropertyNamingStrategy")) |
| 41 | + .invoke(objectMapper, namingStrategy); |
| 42 | + } catch (Exception e) { |
| 43 | + throw new RuntimeException("Failed to set snake_case naming strategy", e); |
| 44 | + } |
| 45 | + |
| 46 | + return objectMapper; |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * Gets the snake case naming strategy, supporting both Jackson 2.12+ and earlier versions. |
| 51 | + */ |
| 52 | + private static Object getSnakeCaseStrategy() { |
| 53 | + try { |
| 54 | + // Try Jackson 2.12+ API first |
| 55 | + Class<?> strategiesClass = Class.forName("com.fasterxml.jackson.databind.PropertyNamingStrategies"); |
| 56 | + return strategiesClass.getField("SNAKE_CASE").get(null); |
| 57 | + } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) { |
| 58 | + try { |
| 59 | + // Fall back to Jackson 2.11 and earlier (deprecated but compatible) |
| 60 | + Class<?> strategyClass = Class.forName("com.fasterxml.jackson.databind.PropertyNamingStrategy"); |
| 61 | + return strategyClass.getField("SNAKE_CASE").get(null); |
| 62 | + } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException ex) { |
| 63 | + throw new RuntimeException("Unable to find snake_case naming strategy in Jackson", ex); |
| 64 | + } |
| 65 | + } |
| 66 | + } |
29 | 67 |
|
30 | 68 | public <T> String serialize(T payload) { |
31 | 69 | mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); |
|
0 commit comments