杰森杰克逊不寻常的地图序列化

时间:2015-11-19 07:14:05

标签: java json jackson

假设我有以下结构:

public class SomeClass {
private String id;
@JsonProperty("key-value")
private Map<String, Object> keyValue;}

显然,它将被序列化为

 {
   "id" : "id1", 
   "key-value" : 
    {"key1" : "value1",
    "key2 : "value2"}
 }

是否有可能像这样代表它?

 {
   "id" : "id1", 
   "key1" : "value1",
   "key2 : "value2"
 }

提前致谢!

1 个答案:

答案 0 :(得分:1)

在Jackson的自定义序列化器的帮助下很有可能:

  1. @JsonSerialize annoation添加到您的POJO:
  2. (还添加了必要的ctor和getters)

    @JsonSerialize(using = SomeClassSerializer.class)
    public static class SomeClass {
        private String id;
        @JsonProperty("key-value")
        private Map<String, Object> keyValue;
    
        public SomeClass(String id, Map<String, Object> keyValue) {
            this.id = id;
            this.keyValue = keyValue;
        }
        public String getId() { return id; }
        public Map<String, Object> getKeyValue() { return keyValue; }
    }
    
    1. 自定义序列化程序如下所示:
    2. public class SomeClassSerializer extends JsonSerializer<SomeClass>
      {
          @Override
          public void serialize(SomeClass sc, JsonGenerator gen, SerializerProvider serializers)
                  throws IOException, JsonProcessingException
          {
              gen.writeStartObject();
              // write id propertry
              gen.writeStringField("id", sc.getId());   
              // loop on keyValue entries, write each as property
              for (Map.Entry<String, Object> keyValueEntry : sc.getKeyValue().entrySet()) {
                  gen.writeObjectField(keyValueEntry.getKey(), keyValueEntry.getValue());
              }
              gen.writeEndObject();
          }
      }
      
      1. 调用杰克逊的映射器是以通常的方式完成的:
      2. public static void main(String[] args)
        {
            Map<String, Object> keyValue = new HashMap<>();
            keyValue.put("key1", "value1");
            keyValue.put("key2", "value2");
            keyValue.put("key3", new Integer(10));
            SomeClass sc = new SomeClass("id1", keyValue);
        
            try {
                new ObjectMapper().writeValue(System.out, sc);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        

        输出:

        {"id":"id1","key1":"value1","key2":"value2","key3":10}