Example #1
0
  /** Method called to serialize fields, when the value type is not statically known. */
  public void serializeFields(Map<?, ?> value, JsonGenerator jgen, SerializerProvider provider)
      throws IOException, JsonGenerationException {
    // If value type needs polymorphic type handling, some more work needed:
    if (_valueTypeSerializer != null) {
      serializeTypedFields(value, jgen, provider);
      return;
    }
    final JsonSerializer<Object> keySerializer = _keySerializer;

    final HashSet<String> ignored = _ignoredEntries;
    final boolean skipNulls = !provider.isEnabled(SerializationFeature.WRITE_NULL_MAP_VALUES);

    PropertySerializerMap serializers = _dynamicValueSerializers;

    for (Map.Entry<?, ?> entry : value.entrySet()) {
      Object valueElem = entry.getValue();
      // First, serialize key
      Object keyElem = entry.getKey();
      if (keyElem == null) {
        provider.findNullKeySerializer(_keyType, _property).serialize(null, jgen, provider);
      } else {
        // [JACKSON-314] skip entries with null values?
        if (skipNulls && valueElem == null) continue;
        // One twist: is entry ignorable? If so, skip
        if (ignored != null && ignored.contains(keyElem)) continue;
        keySerializer.serialize(keyElem, jgen, provider);
      }

      // And then value
      if (valueElem == null) {
        provider.defaultSerializeNull(jgen);
      } else {
        Class<?> cc = valueElem.getClass();
        JsonSerializer<Object> serializer = serializers.serializerFor(cc);
        if (serializer == null) {
          if (_valueType.hasGenericTypes()) {
            serializer =
                _findAndAddDynamic(
                    serializers, provider.constructSpecializedType(_valueType, cc), provider);
          } else {
            serializer = _findAndAddDynamic(serializers, cc, provider);
          }
          serializers = _dynamicValueSerializers;
        }
        try {
          serializer.serialize(valueElem, jgen, provider);
        } catch (Exception e) {
          // [JACKSON-55] Need to add reference information
          String keyDesc = "" + keyElem;
          wrapAndThrow(provider, e, value, keyDesc);
        }
      }
    }
  }
 private final JsonSerializer<Object> _findSerializer(SerializerProvider provider, Object value)
     throws JsonMappingException {
   final Class<?> cc = value.getClass();
   JsonSerializer<Object> valueSer = _dynamicValueSerializers.serializerFor(cc);
   if (valueSer != null) {
     return valueSer;
   }
   if (_valueType.hasGenericTypes()) {
     return _findAndAddDynamic(
         _dynamicValueSerializers, provider.constructSpecializedType(_valueType, cc), provider);
   }
   return _findAndAddDynamic(_dynamicValueSerializers, cc, provider);
 }