MATSIM
StringCollectionConverter.java
Go to the documentation of this file.
1 package org.matsim.utils.objectattributes.attributeconverters;
2 
3 import com.fasterxml.jackson.core.JsonProcessingException;
4 import com.fasterxml.jackson.databind.ObjectMapper;
5 import com.fasterxml.jackson.databind.type.CollectionType;
6 import com.fasterxml.jackson.databind.type.TypeFactory;
8 
9 import java.util.Collection;
10 import java.util.Collections;
11 
12 public class StringCollectionConverter implements AttributeConverter<Collection<String>> {
13 
14  private static final ObjectMapper mapper = new ObjectMapper();
15  private static final CollectionType collectionType = TypeFactory.defaultInstance().constructCollectionType(Collection.class, String.class);
16 
17  @Override
18  public Collection<String> convert(String value) {
19  try {
20  return Collections.unmodifiableCollection(mapper.readValue(value, collectionType));
21  } catch (JsonProcessingException e) {
22  throw new RuntimeException(e);
23  }
24  }
25 
26  @Override
27  public String convertToString(Object o) {
28  try {
29  return mapper.writeValueAsString(o);
30  } catch (JsonProcessingException e) {
31  throw new RuntimeException(e);
32  }
33  }
34 }