Java 17 - Difficulty with Custom Serialization of Immutable Collections in Jackson
I tried several approaches but none seem to work. I'm learning this framework and After trying multiple solutions online, I still can't figure this out. I've been struggling with this for a few days now and could really use some help. I'm trying to serialize an immutable collection in Java 17 using Jackson, but I'm working with a `JsonMappingException` when Jackson tries to serialize a `List` that is defined as immutable. Here's the relevant part of my code: ```java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.util.Collections; import java.util.List; public class MyData { @JsonSerialize private final List<String> items; public MyData(List<String> items) { this.items = Collections.unmodifiableList(items); } public List<String> getItems() { return items; } } ``` When I serialize an instance of `MyData` like this: ```java import com.fasterxml.jackson.databind.ObjectMapper; public class Main { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); MyData data = new MyData(List.of("item1", "item2", "item3")); String jsonString = mapper.writeValueAsString(data); System.out.println(jsonString); } } ``` I get the following behavior: ``` com.fasterxml.jackson.databind.JsonMappingException: Invalid type definition for property "items": want to construct instance of `java.util.List` (no Creators, like default constructor, exist): can only instantiate non-static inner classes by using default constructor ``` I understand that Jackson has trouble with immutable types because it need to find a way to instantiate them. I've tried adding a custom serializer by creating a class that extends `JsonSerializer<List>` but I need to seem to get it to work properly. How can I properly serialize this immutable list? Is there a recommended way to handle this with Jackson to avoid such errors? My development environment is macOS. Any ideas what could be causing this? I'm working on a CLI tool that needs to handle this. My team is using Java for this CLI tool. What would be the recommended way to handle this?