|
1 | 1 | /** |
2 | 2 | * |
3 | | - * Copyright 2016-2017, 2019, Optimizely and contributors |
| 3 | + * Copyright 2016-2017, 2019, 2025 Optimizely and contributors |
4 | 4 | * |
5 | 5 | * Licensed under the Apache License, Version 2.0 (the "License"); |
6 | 6 | * you may not use this file except in compliance with the License. |
|
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.PropertyNamingStrategy; |
23 | 22 |
|
24 | 23 | class JacksonSerializer implements Serializer { |
25 | 24 |
|
26 | | - private ObjectMapper mapper = |
27 | | - new ObjectMapper().setPropertyNamingStrategy( |
28 | | - PropertyNamingStrategy.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 | + objectMapper.setPropertyNamingStrategy((com.fasterxml.jackson.databind.PropertyNamingStrategy) namingStrategy); |
| 36 | + return objectMapper; |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Gets the snake case naming strategy, supporting both Jackson 2.12+ and earlier versions. |
| 41 | + */ |
| 42 | + private static Object getSnakeCaseStrategy() { |
| 43 | + try { |
| 44 | + // Try Jackson 2.12+ API first |
| 45 | + Class<?> strategiesClass = Class.forName("com.fasterxml.jackson.databind.PropertyNamingStrategies"); |
| 46 | + return strategiesClass.getField("SNAKE_CASE").get(null); |
| 47 | + } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) { |
| 48 | + try { |
| 49 | + // Fall back to Jackson 2.11 and earlier (deprecated but compatible) |
| 50 | + Class<?> strategyClass = Class.forName("com.fasterxml.jackson.databind.PropertyNamingStrategy"); |
| 51 | + return strategyClass.getField("SNAKE_CASE").get(null); |
| 52 | + } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException ex) { |
| 53 | + throw new RuntimeException("Unable to find snake_case naming strategy in Jackson", ex); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
29 | 57 |
|
30 | 58 | public <T> String serialize(T payload) { |
31 | 59 | mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); |
|
0 commit comments