public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property)
     throws JsonMappingException {
   JsonSerializer<?> ser = null;
   if (property != null) {
     AnnotatedMember m = property.getMember();
     if (m != null) {
       Object serDef = provider.getAnnotationIntrospector().findContentSerializer(m);
       if (serDef != null) {
         ser = provider.serializerInstance(m, serDef);
       }
     }
   }
   if (ser == null) {
     ser = this._elementSerializer;
   }
   ser = findConvertingContentSerializer(provider, property, ser);
   if (ser == null) {
     ser = provider.findValueSerializer(String.class, property);
   } else {
     ser = provider.handleSecondaryContextualization(ser, property);
   }
   if (isDefaultSerializer(ser)) {
     ser = null;
   }
   return ser == this._elementSerializer ? this : new StringArraySerializer(this, property, ser);
 }
 public JsonNode getSchema(SerializerProvider paramSerializerProvider, Type paramType)
     throws JsonMappingException {
   ObjectNode localObjectNode = createSchemaNode("array", true);
   if (paramType != null) {
     paramType = paramSerializerProvider.constructType(paramType);
     if (paramType.isArrayType()) {
       paramType = ((ArrayType) paramType).getContentType().getRawClass();
       if (paramType != Object.class) {
         break label54;
       }
       localObjectNode.set("items", JsonSchema.getDefaultSchemaNode());
     }
   }
   return localObjectNode;
   label54:
   paramType = paramSerializerProvider.findValueSerializer(paramType, this._property);
   if ((paramType instanceof SchemaAware)) {}
   for (paramSerializerProvider =
           ((SchemaAware) paramType).getSchema(paramSerializerProvider, null);
       ;
       paramSerializerProvider = JsonSchema.getDefaultSchemaNode()) {
     localObjectNode.set("items", paramSerializerProvider);
     return localObjectNode;
   }
 }
  /**
   * Method called to serialize fields, when the value type is statically known, so that value
   * serializer is passed and does not need to be fetched from provider.
   */
  public void serializeFieldsUsing(
      Map<?, ?> value, JsonGenerator gen, SerializerProvider provider, JsonSerializer<Object> ser)
      throws IOException {
    final JsonSerializer<Object> keySerializer = _keySerializer;
    final Set<String> ignored = _ignoredEntries;
    final TypeSerializer typeSer = _valueTypeSerializer;

    for (Map.Entry<?, ?> entry : value.entrySet()) {
      Object keyElem = entry.getKey();
      if (ignored != null && ignored.contains(keyElem)) continue;

      if (keyElem == null) {
        provider.findNullKeySerializer(_keyType, _property).serialize(null, gen, provider);
      } else {
        keySerializer.serialize(keyElem, gen, provider);
      }
      final Object valueElem = entry.getValue();
      if (valueElem == null) {
        provider.defaultSerializeNull(gen);
      } else {
        try {
          if (typeSer == null) {
            ser.serialize(valueElem, gen, provider);
          } else {
            ser.serializeWithType(valueElem, gen, provider, typeSer);
          }
        } catch (Exception e) {
          wrapAndThrow(provider, e, value, String.valueOf(keyElem));
        }
      }
    }
  }
  protected void _writeNullKeyedEntry(JsonGenerator gen, SerializerProvider provider, Object value)
      throws IOException {
    JsonSerializer<Object> keySerializer = provider.findNullKeySerializer(_keyType, _property);
    JsonSerializer<Object> valueSer;
    if (value == null) {
      if (_suppressNulls) {
        return;
      }
      valueSer = provider.getDefaultNullValueSerializer();
    } else {
      valueSer = _valueSerializer;
      if (valueSer == null) {
        valueSer = _findSerializer(provider, value);
      }
      if (_suppressableValue == MARKER_FOR_EMPTY) {
        if (valueSer.isEmpty(provider, value)) {
          return;
        }
      } else if ((_suppressableValue != null) && (_suppressableValue.equals(value))) {
        return;
      }
    }

    try {
      keySerializer.serialize(null, gen, provider);
      valueSer.serialize(value, gen, provider);
    } catch (Exception e) {
      wrapAndThrow(provider, e, value, "");
    }
  }
 protected boolean _useStatic(
     SerializerProvider provider, BeanProperty property, JavaType referredType) {
   // First: no serializer for `Object.class`, must be dynamic
   if (referredType.isJavaLangObject()) {
     return false;
   }
   // but if type is final, might as well fetch
   if (referredType.isFinal()) { // or should we allow annotation override? (only if requested...)
     return true;
   }
   // also: if indicated by typing, should be considered static
   if (referredType.useStaticType()) {
     return true;
   }
   // if neither, maybe explicit annotation?
   AnnotationIntrospector intr = provider.getAnnotationIntrospector();
   if ((intr != null) && (property != null)) {
     Annotated ann = property.getMember();
     if (ann != null) {
       JsonSerialize.Typing t = intr.findSerializationTyping(property.getMember());
       if (t == JsonSerialize.Typing.STATIC) {
         return true;
       }
       if (t == JsonSerialize.Typing.DYNAMIC) {
         return false;
       }
     }
   }
   // and finally, may be forced by global static typing (unlikely...)
   return provider.isEnabled(MapperFeature.USE_STATIC_TYPING);
 }
 @Override
 public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property)
     throws JsonMappingException {
   TypeSerializer vts = _valueTypeSerializer;
   if (vts != null) {
     vts = vts.forProperty(property);
   }
   JsonSerializer<?> ser = findContentSerializer(provider, property);
   if (ser == null) {
     ser = _valueSerializer;
     if (ser == null) {
       // A few conditions needed to be able to fetch serializer here:
       if (_useStatic(provider, property, _referredType)) {
         ser = _findSerializer(provider, _referredType, property);
       }
     } else {
       ser = provider.handlePrimaryContextualization(ser, property);
     }
   }
   // Also: may want to have more refined exclusion based on referenced value
   JsonInclude.Include contentIncl = _contentInclusion;
   if (property != null) {
     JsonInclude.Value incl = property.findPropertyInclusion(provider.getConfig(), Optional.class);
     JsonInclude.Include newIncl = incl.getContentInclusion();
     if ((newIncl != contentIncl) && (newIncl != JsonInclude.Include.USE_DEFAULTS)) {
       contentIncl = newIncl;
     }
   }
   return withResolved(property, vts, ser, _unwrapper, contentIncl);
 }
  /**
   * Helper method used when we have a JSON Filter to use for potentially filtering out Map entries.
   *
   * @since 2.5
   */
  public void serializeFilteredFields(
      Map<?, ?> value,
      JsonGenerator gen,
      SerializerProvider provider,
      PropertyFilter filter,
      Object suppressableValue) // since 2.5
      throws IOException {
    final Set<String> ignored = _ignoredEntries;
    final MapProperty prop = new MapProperty(_valueTypeSerializer, _property);
    final boolean checkEmpty = (MARKER_FOR_EMPTY == suppressableValue);

    for (Map.Entry<?, ?> entry : value.entrySet()) {
      // First, serialize key; unless ignorable by key
      final Object keyElem = entry.getKey();
      if (ignored != null && ignored.contains(keyElem)) continue;

      JsonSerializer<Object> keySerializer;
      if (keyElem == null) {
        keySerializer = provider.findNullKeySerializer(_keyType, _property);
      } else {
        keySerializer = _keySerializer;
      }
      // or by value; nulls often suppressed
      final Object valueElem = entry.getValue();

      JsonSerializer<Object> valueSer;
      // And then value
      if (valueElem == null) {
        if (_suppressNulls) {
          continue;
        }
        valueSer = provider.getDefaultNullValueSerializer();
      } else {
        valueSer = _valueSerializer;
        if (valueSer == null) {
          valueSer = _findSerializer(provider, valueElem);
        }
        // also may need to skip non-empty values:
        if (checkEmpty) {
          if (valueSer.isEmpty(provider, valueElem)) {
            continue;
          }
        } else if (suppressableValue != null) {
          if (suppressableValue.equals(valueElem)) {
            continue;
          }
        }
      }
      // and with that, ask filter to handle it
      prop.reset(keyElem, keySerializer, valueSer);
      try {
        filter.serializeAsField(valueElem, gen, provider, prop);
      } catch (Exception e) {
        wrapAndThrow(provider, e, value, String.valueOf(keyElem));
      }
    }
  }
  /** Serialization method called when exclusion filtering needs to be applied. */
  public void serializeOptionalFields(
      Map<?, ?> value, JsonGenerator gen, SerializerProvider provider, Object suppressableValue)
      throws IOException {
    // If value type needs polymorphic type handling, some more work needed:
    if (_valueTypeSerializer != null) {
      serializeTypedFields(value, gen, provider, suppressableValue);
      return;
    }
    final Set<String> ignored = _ignoredEntries;
    final boolean checkEmpty = (MARKER_FOR_EMPTY == suppressableValue);

    for (Map.Entry<?, ?> entry : value.entrySet()) {
      // First find key serializer
      final Object keyElem = entry.getKey();
      JsonSerializer<Object> keySerializer;
      if (keyElem == null) {
        keySerializer = provider.findNullKeySerializer(_keyType, _property);
      } else {
        if (ignored != null && ignored.contains(keyElem)) continue;
        keySerializer = _keySerializer;
      }

      // Then value serializer
      final Object valueElem = entry.getValue();
      JsonSerializer<Object> valueSer;
      if (valueElem == null) {
        if (_suppressNulls) { // all suppressions include null-suppression
          continue;
        }
        valueSer = provider.getDefaultNullValueSerializer();
      } else {
        valueSer = _valueSerializer;
        if (valueSer == null) {
          valueSer = _findSerializer(provider, valueElem);
        }
        // also may need to skip non-empty values:
        if (checkEmpty) {
          if (valueSer.isEmpty(provider, valueElem)) {
            continue;
          }
        } else if (suppressableValue != null) {
          if (suppressableValue.equals(valueElem)) {
            continue;
          }
        }
      }
      // and then serialize, if all went well
      try {
        keySerializer.serialize(keyElem, gen, provider);
        valueSer.serialize(valueElem, gen, provider);
      } catch (Exception e) {
        wrapAndThrow(provider, e, value, String.valueOf(keyElem));
      }
    }
  }
Beispiel #9
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);
        }
      }
    }
  }
  /** @since 2.5 */
  public void serializeTypedFields(
      Map<?, ?> value,
      JsonGenerator gen,
      SerializerProvider provider,
      Object suppressableValue) // since 2.5
      throws IOException {
    final Set<String> ignored = _ignoredEntries;
    final boolean checkEmpty = (MARKER_FOR_EMPTY == suppressableValue);

    for (Map.Entry<?, ?> entry : value.entrySet()) {
      Object keyElem = entry.getKey();
      JsonSerializer<Object> keySerializer;
      if (keyElem == null) {
        keySerializer = provider.findNullKeySerializer(_keyType, _property);
      } else {
        // One twist: is entry ignorable? If so, skip
        if (ignored != null && ignored.contains(keyElem)) continue;
        keySerializer = _keySerializer;
      }
      final Object valueElem = entry.getValue();

      // And then value
      JsonSerializer<Object> valueSer;
      if (valueElem == null) {
        if (_suppressNulls) { // all suppression include null suppression
          continue;
        }
        valueSer = provider.getDefaultNullValueSerializer();
      } else {
        valueSer = _valueSerializer;
        if (valueSer == null) {
          valueSer = _findSerializer(provider, valueElem);
        }
        // also may need to skip non-empty values:
        if (checkEmpty) {
          if (valueSer.isEmpty(provider, valueElem)) {
            continue;
          }
        } else if (suppressableValue != null) {
          if (suppressableValue.equals(valueElem)) {
            continue;
          }
        }
      }
      keySerializer.serialize(keyElem, gen, provider);
      try {
        valueSer.serializeWithType(valueElem, gen, provider, _valueTypeSerializer);
      } catch (Exception e) {
        wrapAndThrow(provider, e, value, String.valueOf(keyElem));
      }
    }
  }
 // !!! TODO: added late in 2.7 in `jackson-databind`: remove from 2.8
 protected JsonSerializer<?> findContentSerializer(
     SerializerProvider serializers, BeanProperty property) throws JsonMappingException {
   if (property != null) {
     AnnotatedMember m = property.getMember();
     final AnnotationIntrospector intr = serializers.getAnnotationIntrospector();
     if (m != null) {
       Object serDef = intr.findContentSerializer(m);
       if (serDef != null) {
         return serializers.serializerInstance(m, serDef);
       }
     }
   }
   return null;
 }
 @Override
 public JsonArrayFormatVisitor expectArrayFormat(JavaType type) throws JsonMappingException {
   serializerProvider
       .findValueSerializer(type.getContentType())
       .acceptJsonFormatVisitor(createSubtraverser(baseName), type.getContentType());
   return new JsonArrayFormatVisitor.Base(serializerProvider);
 }
  /**
   * Main serialization method needs to be overridden to allow XML-specific extra handling, such as
   * indication of whether to write attributes or elements.
   */
  @Override
  protected void serializeFields(Object bean, JsonGenerator jgen0, SerializerProvider provider)
      throws IOException, JsonGenerationException {
    // 19-Aug-2013, tatu: During 'convertValue()', need to skip
    if (!(jgen0 instanceof ToXmlGenerator)) {
      super.serializeFields(bean, jgen0, provider);
      return;
    }

    final ToXmlGenerator xgen = (ToXmlGenerator) jgen0;
    final BeanPropertyWriter[] props;
    if (_filteredProps != null && provider.getActiveView() != null) {
      props = _filteredProps;
    } else {
      props = _props;
    }

    final int attrCount = _attributeCount;
    if (attrCount > 0) {
      xgen.setNextIsAttribute(true);
    }
    final int textIndex = _textPropertyIndex;
    final QName[] xmlNames = _xmlNames;
    int i = 0;

    try {
      for (final int len = props.length; i < len; ++i) {
        if (i == attrCount) {
          xgen.setNextIsAttribute(false);
        }
        // also: if this is property to write as text ("unwrap"), need to:
        if (i == textIndex) {
          xgen.setNextIsUnwrapped(true);
        }
        xgen.setNextName(xmlNames[i]);
        BeanPropertyWriter prop = props[i];
        if (prop != null) { // can have nulls in filtered list
          prop.serializeAsField(bean, xgen, provider);
        }
        // Reset to avoid next value being written as unwrapped,
        // for example when property is suppressed
        if (i == textIndex) {
          xgen.setNextIsUnwrapped(false);
        }
      }
      if (_anyGetterWriter != null) {
        _anyGetterWriter.getAndSerialize(bean, xgen, provider);
      }
    } catch (Exception e) {
      String name = (i == props.length) ? "[anySetter]" : props[i].getName();
      wrapAndThrow(provider, e, bean, name);
    } catch (StackOverflowError e) { // Bit tricky, can't do more calls as stack is full; so:
      JsonMappingException mapE =
          new JsonMappingException("Infinite recursion (StackOverflowError)");
      String name = (i == props.length) ? "[anySetter]" : props[i].getName();
      mapE.prependPath(new JsonMappingException.Reference(bean, name));
      throw mapE;
    }
  }
 public JsonSerializer<?> createContextual(
     SerializerProvider paramSerializerProvider, BeanProperty paramBeanProperty)
     throws JsonMappingException {
   Object localObject2 = null;
   Object localObject1 = localObject2;
   if (paramBeanProperty != null) {
     AnnotatedMember localAnnotatedMember = paramBeanProperty.getMember();
     localObject1 = localObject2;
     if (localAnnotatedMember != null) {
       Object localObject3 =
           paramSerializerProvider
               .getAnnotationIntrospector()
               .findContentSerializer(localAnnotatedMember);
       localObject1 = localObject2;
       if (localObject3 != null) {
         localObject1 =
             paramSerializerProvider.serializerInstance(localAnnotatedMember, localObject3);
       }
     }
   }
   localObject2 = localObject1;
   if (localObject1 == null) {
     localObject2 = this._valueSerializer;
   }
   localObject1 =
       findConvertingContentSerializer(
           paramSerializerProvider, paramBeanProperty, (JsonSerializer) localObject2);
   if (localObject1 == null) {
     if (!this._staticTyping) {
       break label111;
     }
     paramSerializerProvider =
         withValueSerializer(
             paramBeanProperty,
             paramSerializerProvider.findValueSerializer(this._valueType, paramBeanProperty));
   }
   label111:
   do {
     return paramSerializerProvider;
     localObject1 =
         paramSerializerProvider.handleSecondaryContextualization(
             (JsonSerializer) localObject1, paramBeanProperty);
     paramSerializerProvider = this;
   } while (localObject1 == this._valueSerializer);
   return withValueSerializer(paramBeanProperty, (JsonSerializer) localObject1);
 }
 @Override
 public void serializeWithType(
     byte[] value, JsonGenerator g, SerializerProvider provider, TypeSerializer typeSer)
     throws IOException {
   typeSer.writeTypePrefixForScalar(value, g);
   g.writeBinary(provider.getConfig().getBase64Variant(), value, 0, value.length);
   typeSer.writeTypeSuffixForScalar(value, g);
 }
Beispiel #16
0
  protected void serializeTypedFields(
      Map<?, ?> value, JsonGenerator jgen, SerializerProvider provider)
      throws IOException, JsonGenerationException {
    final JsonSerializer<Object> keySerializer = _keySerializer;
    JsonSerializer<Object> prevValueSerializer = null;
    Class<?> prevValueClass = null;
    final HashSet<String> ignored = _ignoredEntries;
    final boolean skipNulls = !provider.isEnabled(SerializationFeature.WRITE_NULL_MAP_VALUES);

    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] also may need to 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> currSerializer;
        if (cc == prevValueClass) {
          currSerializer = prevValueSerializer;
        } else {
          currSerializer = provider.findValueSerializer(cc, _property);
          prevValueSerializer = currSerializer;
          prevValueClass = cc;
        }
        try {
          currSerializer.serializeWithType(valueElem, jgen, provider, _valueTypeSerializer);
        } catch (Exception e) {
          // [JACKSON-55] Need to add reference information
          String keyDesc = "" + keyElem;
          wrapAndThrow(provider, e, value, keyDesc);
        }
      }
    }
  }
 public void serializeTypedContents(
     Object[] paramArrayOfObject,
     JsonGenerator paramJsonGenerator,
     SerializerProvider paramSerializerProvider)
     throws IOException {
   int k = paramArrayOfObject.length;
   TypeSerializer localTypeSerializer = this._valueTypeSerializer;
   int j = 0;
   int i = 0;
   Object localObject1 = null;
   for (; ; ) {
     try {
       PropertySerializerMap localPropertySerializerMap = this._dynamicSerializers;
       if (i < k) {
         Object localObject2 = paramArrayOfObject[i];
         if (localObject2 == null) {
           localObject1 = localObject2;
           j = i;
           paramSerializerProvider.defaultSerializeNull(paramJsonGenerator);
         } else {
           localObject1 = localObject2;
           j = i;
           Class localClass = localObject2.getClass();
           localObject1 = localObject2;
           j = i;
           JsonSerializer localJsonSerializer2 =
               localPropertySerializerMap.serializerFor(localClass);
           JsonSerializer localJsonSerializer1 = localJsonSerializer2;
           if (localJsonSerializer2 == null) {
             localObject1 = localObject2;
             j = i;
             localJsonSerializer1 =
                 _findAndAddDynamic(
                     localPropertySerializerMap, localClass, paramSerializerProvider);
           }
           localObject1 = localObject2;
           j = i;
           localJsonSerializer1.serializeWithType(
               localObject2, paramJsonGenerator, paramSerializerProvider, localTypeSerializer);
         }
       }
     } catch (IOException paramArrayOfObject) {
       throw paramArrayOfObject;
     } catch (Exception paramArrayOfObject) {
       if (((paramArrayOfObject instanceof InvocationTargetException))
           && (paramArrayOfObject.getCause() != null)) {
         paramArrayOfObject = paramArrayOfObject.getCause();
         continue;
       }
       if ((paramArrayOfObject instanceof Error)) {
         throw ((Error) paramArrayOfObject);
       }
       throw JsonMappingException.wrapWithPath(paramArrayOfObject, localObject1, j);
     }
     return;
     i += 1;
   }
 }
 @Override
 public void serialize(
     ObjectId objectId, BsonGenerator bsonGenerator, SerializerProvider serializerProvider)
     throws IOException {
   if (objectId == null) {
     serializerProvider.defaultSerializeNull(bsonGenerator);
   } else {
     bsonGenerator.writeObjectId(objectId);
   }
 }
 @Override
 public void serialize(Symbol value, JsonGenerator gen, SerializerProvider serializerProvider)
     throws IOException {
   if (value == null) {
     serializerProvider.defaultSerializeNull(gen);
   } else if (gen instanceof BsonGenerator) {
     BsonGenerator bgen = (BsonGenerator) gen;
     bgen.writeSymbol(value);
   } else {
     gen.writeString(value.getSymbol());
   }
 }
 private void serializeContentsSlow(
     String[] value, JsonGenerator jgen, SerializerProvider provider, JsonSerializer<Object> ser)
     throws IOException, JsonGenerationException {
   int len = value.length;
   for (int i = 0; i < len; i++) {
     if (value[i] == null) {
       provider.defaultSerializeNull(jgen);
     } else {
       ser.serialize(value[i], jgen, provider);
     }
   }
 }
  /**
   * General-purpose serialization for contents, where we do not necessarily know the value
   * serialization, but we do know that no value suppression is needed (which simplifies processing
   * a bit)
   */
  public void serializeFields(Map<?, ?> value, JsonGenerator gen, SerializerProvider provider)
      throws IOException {
    // If value type needs polymorphic type handling, some more work needed:
    if (_valueTypeSerializer != null) {
      serializeTypedFields(value, gen, provider, null);
      return;
    }
    final JsonSerializer<Object> keySerializer = _keySerializer;
    final Set<String> ignored = _ignoredEntries;
    Object keyElem = null;

    try {
      for (Map.Entry<?, ?> entry : value.entrySet()) {
        Object valueElem = entry.getValue();
        // First, serialize key
        keyElem = entry.getKey();
        if (keyElem == null) {
          provider.findNullKeySerializer(_keyType, _property).serialize(null, gen, provider);
        } else {
          // One twist: is entry ignorable? If so, skip
          if ((ignored != null) && ignored.contains(keyElem)) {
            continue;
          }
          keySerializer.serialize(keyElem, gen, provider);
        }
        // And then value
        if (valueElem == null) {
          provider.defaultSerializeNull(gen);
          continue;
        }
        JsonSerializer<Object> serializer = _valueSerializer;
        if (serializer == null) {
          serializer = _findSerializer(provider, valueElem);
        }
        serializer.serialize(valueElem, gen, provider);
      }
    } catch (Exception e) { // Add reference information
      wrapAndThrow(provider, e, value, String.valueOf(keyElem));
    }
  }
 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);
 }
  // need to override as we must get unwrapping instance...
  @Override
  protected JsonSerializer<Object> _findAndAddDynamic(
      PropertySerializerMap map, Class<?> type, SerializerProvider provider)
      throws JsonMappingException {
    JsonSerializer<Object> serializer;
    if (_nonTrivialBaseType != null) {
      JavaType subtype = provider.constructSpecializedType(_nonTrivialBaseType, type);
      serializer = provider.findValueSerializer(subtype, this);
    } else {
      serializer = provider.findValueSerializer(type, this);
    }
    NameTransformer t = _nameTransformer;
    if (serializer.isUnwrappingSerializer()) {
      t =
          NameTransformer.chainedTransformer(
              t, ((UnwrappingBeanSerializer) serializer)._nameTransformer);
    }
    serializer = serializer.unwrappingSerializer(t);

    _dynamicSerializers = _dynamicSerializers.newWith(type, serializer);
    return serializer;
  }
 @Override
 public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property)
     throws JsonMappingException {
   /* 29-Sep-2012, tatu: Actually, we need to do much more contextual
    *    checking here since we finally know for sure the property,
    *    and it may have overrides
    */
   JsonSerializer<?> ser = null;
   // First: if we have a property, may have property-annotation overrides
   if (property != null) {
     AnnotatedMember m = property.getMember();
     if (m != null) {
       Object serDef = provider.getAnnotationIntrospector().findContentSerializer(m);
       if (serDef != null) {
         ser = provider.serializerInstance(m, serDef);
       }
     }
   }
   if (ser == null) {
     ser = _serializer;
   }
   // #124: May have a content converter
   ser = findConvertingContentSerializer(provider, property, ser);
   if (ser == null) {
     ser = provider.findValueSerializer(String.class, property);
   } else if (ser instanceof ContextualSerializer) {
     ser = ((ContextualSerializer) ser).createContextual(provider, property);
   }
   // Optimization: default serializer just writes String, so we can avoid a call:
   if (isDefaultSerializer(ser)) {
     ser = null;
   }
   // note: will never have TypeSerializer, because Strings are "natural" type
   if (ser == _serializer) {
     return this;
   }
   return new IndexedStringListSerializer(ser);
 }
Beispiel #25
0
  //  @Override
  public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property)
      throws JsonMappingException {
    /* 29-Sep-2012, tatu: Actually, we need to do much more contextual
     *    checking here since we finally know for sure the property,
     *    and it may have overrides
     */
    JsonSerializer<?> ser = null;
    JsonSerializer<?> keySer = null;

    // First: if we have a property, may have property-annotation overrides
    if (property != null) {
      AnnotatedMember m = property.getMember();
      if (m != null) {
        Object serDef;
        final AnnotationIntrospector intr = provider.getAnnotationIntrospector();
        serDef = intr.findKeySerializer(m);
        if (serDef != null) {
          keySer = provider.serializerInstance(m, serDef);
        }
        serDef = intr.findContentSerializer(m);
        if (serDef != null) {
          ser = provider.serializerInstance(m, serDef);
        }
      }
    }
    if (ser == null) {
      ser = _valueSerializer;
    }
    if (ser == null) {
      // 30-Sep-2012, tatu: One more thing -- if explicit content type is annotated,
      //   we can consider it a static case as well.
      if (_valueTypeIsStatic || hasContentTypeAnnotation(provider, property)) {
        ser = provider.findValueSerializer(_valueType, property);
      }
    } else if (ser instanceof ContextualSerializer) {
      ser = ((ContextualSerializer) ser).createContextual(provider, property);
    }
    if (keySer == null) {
      keySer = _keySerializer;
    }
    if (keySer == null) {
      keySer = provider.findKeySerializer(_keyType, property);
    } else if (keySer instanceof ContextualSerializer) {
      keySer = ((ContextualSerializer) keySer).createContextual(provider, property);
    }
    HashSet<String> ignored = this._ignoredEntries;
    AnnotationIntrospector intr = provider.getAnnotationIntrospector();
    if (intr != null && property != null) {
      String[] moreToIgnore = intr.findPropertiesToIgnore(property.getMember());
      if (moreToIgnore != null) {
        ignored = (ignored == null) ? new HashSet<String>() : new HashSet<String>(ignored);
        for (String str : moreToIgnore) {
          ignored.add(str);
        }
      }
    }
    return withResolved(property, keySer, ser, ignored);
  }
 @Override
 public void serialize(DateMidnight dt, JsonGenerator jgen, SerializerProvider provider)
     throws IOException, JsonGenerationException {
   if (provider.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) {
     // same as with other date-only values
     jgen.writeStartArray();
     jgen.writeNumber(dt.year().get());
     jgen.writeNumber(dt.monthOfYear().get());
     jgen.writeNumber(dt.dayOfMonth().get());
     jgen.writeEndArray();
   } else {
     jgen.writeString(format.print(dt));
   }
 }
Beispiel #27
0
  /**
   * Method called to serialize fields, when the value type is statically known, so that value
   * serializer is passed and does not need to be fetched from provider.
   */
  protected void serializeFieldsUsing(
      Map<?, ?> value, JsonGenerator jgen, SerializerProvider provider, JsonSerializer<Object> ser)
      throws IOException, JsonGenerationException {
    final JsonSerializer<Object> keySerializer = _keySerializer;
    final HashSet<String> ignored = _ignoredEntries;
    final TypeSerializer typeSer = _valueTypeSerializer;
    final boolean skipNulls = !provider.isEnabled(SerializationFeature.WRITE_NULL_MAP_VALUES);

    for (Map.Entry<?, ?> entry : value.entrySet()) {
      Object valueElem = entry.getValue();
      Object keyElem = entry.getKey();
      if (keyElem == null) {
        provider.findNullKeySerializer(_keyType, _property).serialize(null, jgen, provider);
      } else {
        // [JACKSON-314] also may need to skip entries with null values
        if (skipNulls && valueElem == null) continue;
        if (ignored != null && ignored.contains(keyElem)) continue;
        keySerializer.serialize(keyElem, jgen, provider);
      }
      if (valueElem == null) {
        provider.defaultSerializeNull(jgen);
      } else {
        try {
          if (typeSer == null) {
            ser.serialize(valueElem, jgen, provider);
          } else {
            ser.serializeWithType(valueElem, jgen, provider, typeSer);
          }
        } catch (Exception e) {
          // [JACKSON-55] Need to add reference information
          String keyDesc = "" + keyElem;
          wrapAndThrow(provider, e, value, keyDesc);
        }
      }
    }
  }
 public JsonNode getSchema(SerializerProvider paramSerializerProvider, Type paramType)
     throws JsonMappingException {
   ObjectNode localObjectNode1 = createSchemaNode("object", true);
   if ((paramType instanceof ParameterizedType)) {
     Object localObject = ((ParameterizedType) paramType).getActualTypeArguments();
     if (localObject.length == 2) {
       paramType = paramSerializerProvider.constructType(localObject[0]);
       localObject = paramSerializerProvider.constructType(localObject[1]);
       ObjectNode localObjectNode2 = JsonNodeFactory.instance.objectNode();
       Enum[] arrayOfEnum = (Enum[]) paramType.getRawClass().getEnumConstants();
       int j = arrayOfEnum.length;
       int i = 0;
       if (i < j) {
         Enum localEnum = arrayOfEnum[i];
         paramType =
             paramSerializerProvider.findValueSerializer(
                 ((JavaType) localObject).getRawClass(), this._property);
         if ((paramType instanceof SchemaAware)) {}
         for (paramType = ((SchemaAware) paramType).getSchema(paramSerializerProvider, null);
             ;
             paramType = JsonSchema.getDefaultSchemaNode()) {
           localObjectNode2.set(
               paramSerializerProvider
                   .getConfig()
                   .getAnnotationIntrospector()
                   .findEnumValue(localEnum),
               paramType);
           i += 1;
           break;
         }
       }
       localObjectNode1.set("properties", localObjectNode2);
     }
   }
   return localObjectNode1;
 }
 @Override
 public void serializeWithType(
     Optional<?> opt, JsonGenerator gen, SerializerProvider provider, TypeSerializer typeSer)
     throws IOException {
   if (!opt.isPresent()) {
     if (_unwrapper == null) {
       provider.defaultSerializeNull(gen);
     }
     return;
   }
   // Otherwise apply type-prefix/suffix, then std serialize:
   typeSer.writeTypePrefixForScalar(opt, gen, Optional.class);
   serialize(opt, gen, provider);
   typeSer.writeTypeSuffixForScalar(opt, gen);
 }
Beispiel #30
0
 @Override
 public void serialize(Map<?, ?> value, JsonGenerator jgen, SerializerProvider provider)
     throws IOException, JsonGenerationException {
   jgen.writeStartObject();
   if (!value.isEmpty()) {
     if (provider.isEnabled(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)) {
       value = _orderEntries(value);
     }
     if (_valueSerializer != null) {
       serializeFieldsUsing(value, jgen, provider, _valueSerializer);
     } else {
       serializeFields(value, jgen, provider);
     }
   }
   jgen.writeEndObject();
 }