48674

Serialize a custom map with Jackson

I want to serialize a custom Map to JSON.

The class with implements the map interface is the following:

public class MapImpl extends ForwardingMap<String, String> { //ForwardingMap comes from Guava private String specialInfo; private HashMap<String, String> delegate; @Override protected Map<String, String> delegate() { return this.delegate; } // some getters.... }

If I call now

ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File("/somePath/myJson.json"), objectOfMapImpl);

Jackson will serialize the map and ignores the variable specialInfo

I tried some things with a custom implementation of JsonSerializer but I ended up with this snippet:

ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule("someModule"); module.addSerializer(CheapestResponseDates.class, new JsonSerializer<MapImpl>() { @Override public void serialize(final MapImpl value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { CheapestResponseDurations.class); // how to serialize the map here? maybe be in a data node... jgen.writeStartObject(); jgen.writeObjectField("info", value.getInfo()); jgen.writeEndObject(); } }); mapper.registerModule(module);

I am using JDK 1.7 and Jackson 2.3.1

Answer1:

You can leverage the @JsonAnySetter/ @JsonAnyGetter annotations, as described in this blog post. Since, as you mentioned, your custom map class must implement a Map interface, you could extract a separate "bean" interface and tell Jackson to use it instead when serializing via @JsonSerialize(as = ...) annotation.

I've slightly modified you example to illustrate how it could work. Note that if you want to deserialize the json string back to your map object, you may need to do some other tricks.

public class MapSerialize { public static interface MyInterface { String getSpecialInfo(); @JsonAnyGetter Map<String, String> delegate(); } @JsonSerialize(as = MyInterface.class) public static class MyImpl extends ForwardingMap<String, String> implements MyInterface { private String specialInfo; private HashMap<String, String> delegate = new HashMap<String, String>(); public Map<String, String> delegate() { return this.delegate; } @Override public String getSpecialInfo() { return specialInfo; } public void setSpecialInfo(String specialInfo) { this.specialInfo = specialInfo; } @Override public String put(String key, String value) { return delegate.put(key, value); } } public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); MyImpl objectOfMapImpl = new MyImpl(); objectOfMapImpl.setSpecialInfo("specialInfo"); objectOfMapImpl.put("XXX", "YYY"); String json = mapper.writeValueAsString(objectOfMapImpl); System.out.println(json); }

}

Recommend

  • System.Type has no definition for “GetCustomAttribute” in net35
  • StackOverflow exception when using custom JsonConverter and custom ContractResolver
  • access dbcontext in custom Newtonsoft JsonConverter class
  • Json conversion in ASP.NET for CQRS
  • Java JSON library that supports DOM-style access
  • Best way to map json to a Java object
  • Force JObject to serialzie date in “dd-mm-yyyy” format
  • AWS Java SDK is taking old version of jackson jar
  • How to map json to object using spring boot [duplicate]
  • Json.Net TypeNameHandling.Auto and Asp Web Api Controller gives unexpected behaviour
  • \\n is not working in IE text area
  • Regex: Ignore a part of the string
  • Mapping JSON to Java Object return null value
  • Filter log files(_success and _log) in FileSystem.liststatus
  • @RunWith causes Maven to ignore my Test running with my own runner
  • FAILURE: Gradle Build failed with an exception
  • Is it possible to specialize on a static lifetime?
  • How to Compose OSGi Based project with C++ based project?
  • How do I include screenshots of the full page in my serenity report (and not only of the viewport) u
  • iOS - Is this a task for enums?
  • Dependable views in Ember
  • Implementation of RTTI using typeid
  • Cocoa OSX: How can I make an image draggable
  • Why can't I use non-integral types with switch [duplicate]
  • Find longest path less than or equal to given value of an acyclic, directed graph in Python
  • What is the undocumented SessionIdInterface in PHP 5.5?
  • Where these are stored?
  • What's the syntax to inherit documentation from another indexer?
  • abstracting over a collection
  • JSR-330 support in Picocontainer : @Inject … @Named(\"xxx)
  • Can't remove headers after they are sent
  • C++ pointer value changes with static_cast
  • WPF ICommand CanExecute(): RaiseCanExecuteChanged() or automatic handling via DispatchTimer?
  • Updating server-side rendering client-side
  • htaccess rewriting URLs with multiple forward slashes
  • Weird JavaScript statement, what does it mean?
  • How do you troubleshoot character encoding problems?
  • How to format a variable of double type
  • Hits per day in Google Big Query
  • How to Embed XSL into XML