简体   繁体   中英

jackson serialize class literal

I have a class:

package my.package;
public class TreeItem{
    ...
}

When I want to serialize a Class literal like TreeItem.class the jackson serializes it as:

"class my.package.TreeItem"  

I want to serialize it as

"my.package.TreeItem"

EDIT:

public class TreeConfigMap extends HashMap<Class<? extends TreeItem>, Map<String, Object>>{
  //empty
}

TreeController: (a rest controller)

@RequestMapping("/config")
public TreeConfigMap config(...){
  TreeConfigMap config= new TreeConfigMap();
  Map<String,Object> m = new HashMap<>();
  m.put("ali","gholi");
  config.put(TreeItem.class,m);
  return config;
}

The output is:

{"class my.package.TreeItem":{"ali":"gholi"}}

You can use custom key serializer.

Annotate your TreeConfigMap to use custom key serializer

@JsonSerialize(keyUsing = ClassNameSerializer.class)
public static class TreeConfigMap extends HashMap<Class<? extends TreeItem>, Map<String, Object>>{
      //empty
}

Alternatively, you register the serializer with ObjectMapper

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addKeySerializer(Class.class, new ClassNameSerializer());
    mapper.registerModule(simpleModule);
    ...
    mapper.writeValueAsString(treeConfigMap)

Here is serializer code

public static class ClassNameSerializer extends JsonSerializer<Class> {
    @Override
    public void serialize(Class value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeFieldName(value.getCanonicalName());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM