com.fasterxml.jackson.databind.ser.std.StdSerializer Java Examples

The following examples show how to use com.fasterxml.jackson.databind.ser.std.StdSerializer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ASTConstructBodySignature.java    From steady with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public String toJson(){
 final Map<Class<?>, StdSerializer<?>> custom_serializers = new HashMap<Class<?>, StdSerializer<?>>();
 custom_serializers.put(ASTConstructBodySignature.class, new ASTConstructBodySignatureSerializer());
 return JacksonUtil.asJsonString(this, custom_serializers);
 
 /*StringBuilder buffer = new StringBuilder();
   	buffer.append("{\"ast\":[ ");
   	if(fRoot.isRoot()){
   		buffer.append("{");
   		buildJsonElement(fRoot,buffer);
   		if(fRoot.isLeaf())
			buffer.append("}");
		else{
				buffer.append(",\"C\" : [" );
				JSON(fRoot,buffer);
				buffer.append("]}");
		}
   	}

   	buffer.append("]}"); //close off the ast array opened above
   	return buffer.toString();*/
   }
 
Example #2
Source File: ASTSignatureChange.java    From steady with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public String toJSON() {
	final Map<Class<?>, StdSerializer<?>> custom_serializers = new HashMap<Class<?>, StdSerializer<?>>();
	custom_serializers.put(ASTSignatureChange.class, new ASTSignatureChangeSerializer());
	return JacksonUtil.asJsonString(this, custom_serializers);
}
 
Example #3
Source File: JacksonUtil.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes the given object to JSON, thereby using the given {@link StdSerializer}s and the given view {@link Class}.
 *
 * @param _object a {@link java.lang.Object} object.
 * @param _custom_serializers a {@link java.util.Map} object.
 * @param _view a {@link java.lang.Class} object.
 * @return a {@link java.lang.String} object.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String asJsonString(final Object _object, final Map<Class<?>, StdSerializer<?>> _custom_serializers, final Class _view) {
       try {
           final ObjectMapper mapper = new ObjectMapper();
           
           // Register custom serializers
   		final SimpleModule module = new SimpleModule();
   		if(_custom_serializers!=null && !_custom_serializers.isEmpty()) {
   			for(Class clazz: _custom_serializers.keySet()) {
   				module.addSerializer(clazz, _custom_serializers.get(clazz));
   			}
   		}
   		mapper.registerModule(module);
           
   		String jsonContent = null;
   		if(_view==null) {
   			jsonContent = mapper.writeValueAsString(_object);
   		}
   		else {
   			jsonContent = mapper.writerWithView(_view).writeValueAsString(_object);
   		}
           return jsonContent;
       } catch (Exception e) {
           throw new RuntimeException(e);
       }
   }
 
Example #4
Source File: ObjectMapperResolver.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
public ObjectMapperResolver() {
    mapper = new GraviteeMapper();

    //because Permissions are represented as char[]
    mapper.enable(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS);

    // register filter provider
    registerFilterProvider();

    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config,
                                                             final JavaType type,
                                                             BeanDescription beanDesc,
                                                             final JsonDeserializer<?> deserializer) {
            return new JsonDeserializer<Enum>() {
                @Override
                public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                    Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
                    return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
                }
            };
        }
    });
    module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
        @Override
        public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeString(value.name().toLowerCase());
        }
    });
    mapper.registerModule(module);
}
 
Example #5
Source File: ObjectMapperResolver.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
public ObjectMapperResolver() {
    mapper = new GraviteeMapper();

    //because Permissions are represented as char[]
    mapper.enable(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS);

    // register filter provider
    registerFilterProvider();

    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config,
                                                             final JavaType type,
                                                             BeanDescription beanDesc,
                                                             final JsonDeserializer<?> deserializer) {
            return new JsonDeserializer<Enum>() {
                @Override
                public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                    Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
                    return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
                }
            };
        }
    });
    module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
        @Override
        public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeString(value.name().toLowerCase());
        }
    });
    mapper.registerModule(module);
    
    mapper.registerModule(new JavaTimeModule());
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
 
Example #6
Source File: AbstractMetricsDispatcher.java    From gradle-metrics-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Register Jackson module that maps enums as lowercase. Per http://stackoverflow.com/a/24173645.
 */
@SuppressWarnings("rawtypes")
private static void registerEnumModule(ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config,
                                                             final JavaType type,
                                                             BeanDescription beanDesc,
                                                             final JsonDeserializer<?> deserializer) {
            return new JsonDeserializer<Enum>() {
                @Override
                public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                    @SuppressWarnings("unchecked") Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
                    return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
                }
            };
        }
    });
    module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
        @Override
        public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeString(value.name().toLowerCase());
        }
    });
    mapper.registerModule(module);
}
 
Example #7
Source File: ConstantBinarySerializer.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
private static StdSerializer<byte[]> findDelegate() {
  try {
    // Jackson 2.6+
    return newInstance("com.fasterxml.jackson.databind.ser.std.ByteArraySerializer");
  } catch (Throwable t) {
    try {
      return newInstance("com.fasterxml.jackson.databind.ser.std.StdArraySerializers$ByteArraySerializer");
    } catch (Throwable t2) {
      throw new RuntimeException("Unable to find ByteArraySerializer to delegate to", t2);
    }
  }
}
 
Example #8
Source File: StoredAsJsonBinarySerializer.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
private static StdSerializer<byte[]> findDelegate() {
  try {
    // Jackson 2.6+
    return newInstance("com.fasterxml.jackson.databind.ser.std.ByteArraySerializer");
  } catch (Throwable t) {
    try {
      return newInstance("com.fasterxml.jackson.databind.ser.std.StdArraySerializers$ByteArraySerializer");
    } catch (Throwable t2) {
      throw new RuntimeException("Unable to find ByteArraySerializer to delegate to", t2);
    }
  }
}
 
Example #9
Source File: TestModule.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
public TestModule() {
  addSerializer(new StdSerializer<ServiceLoaderBean>(ServiceLoaderBean.class) {

    @Override
    public void serialize(ServiceLoaderBean value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
      jgen.writeStartObject();
      jgen.writeNumberField("id_value", value.getId());
      jgen.writeStringField("name_value", value.getName());
      jgen.writeEndObject();
    }
  });
}
 
Example #10
Source File: FilterableBeanSerializerModifier.java    From caravan with Apache License 2.0 4 votes vote down vote up
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
    FilterableType filterableType = _config.getFilterableType(beanDesc.getBeanClass());
    if (filterableType == null)
        return beanProperties;

    for (final BeanPropertyWriter beanPropertyWriter : beanProperties) {
        final FilterableProperty property = filterableType.getProperty(beanPropertyWriter.getName());
        if (property == null || property.getSerializationFilter() == null)
            continue;

        beanPropertyWriter.assignSerializer(new StdSerializer<Object>(Object.class) {

            private static final long serialVersionUID = 1L;

            @Override
            public void serialize(Object value, JsonGenerator gen, final SerializerProvider provider) throws IOException {
                JsonSerializer<Object> serializer = ConcurrentHashMapValues.getOrAdd(_customSerializers, beanPropertyWriter.getType(),
                        new Func<JsonSerializer<Object>>() {
                            @Override
                            public JsonSerializer<Object> execute() {
                                try {
                                    return BeanSerializerFactory.instance.createSerializer(provider, beanPropertyWriter.getType());
                                } catch (Throwable ex) {
                                    _logger.error("Error occurred when creating custom serializer for type: " + beanPropertyWriter.getType(), ex);
                                    return NullSerializer.instance;
                                }
                            }
                        });

                value = property.getSerializationFilter().filter(property, value);
                if (value == null) {
                    gen.writeNull();
                    return;
                }

                serializer.serialize(value, gen, provider);
            }
        });

        _logger.info("Will apply filter {} for property: {}.", property.getSerializationFilter(), property.name());
    }

    return beanProperties;
}
 
Example #11
Source File: ObjectMapperResolver.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
public ObjectMapperResolver() {
    mapper = new ObjectMapper();

    SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new BeanDeserializerModifier() {
        @Override
        public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config,
                                                             final JavaType type,
                                                             BeanDescription beanDesc,
                                                             final JsonDeserializer<?> deserializer) {
            return new JsonDeserializer<Enum>() {
                @Override
                public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                    Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
                    return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
                }
            };
        }
    });
    module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
        @Override
        public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeString(value.name().toLowerCase());
        }
    });
    module.addSerializer(Instant.class, new StdSerializer<Instant>(Instant.class) {
        @Override
        public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeNumber(instant.toEpochMilli());
        }
    });
    module.addDeserializer(JWK.class, new StdDeserializer<JWK>(JWK.class) {
        @Override
        public JWK deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            JsonNode node = jsonParser.getCodec().readTree(jsonParser);
            String kty = node.get("kty").asText();
            if (kty == null) {
                return null;
            }
            JWK jwk = null;
            switch (kty) {
                case "RSA":
                    jwk = jsonParser.getCodec().treeToValue(node, RSAKey.class);
                    break;
                case "EC":
                    jwk = jsonParser.getCodec().treeToValue(node, ECKey.class);
                    break;
                case "oct":
                    jwk = jsonParser.getCodec().treeToValue(node, OCTKey.class);
                    break;
                case "OKP":
                    jwk = jsonParser.getCodec().treeToValue(node, OKPKey.class);
                    break;
            }
            return jwk;
        }
    });
    mapper.addMixIn(Domain.class, MixIn.class);
    mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.registerModule(module);
    mapper.registerModule(new Jdk8Module());
    mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
}
 
Example #12
Source File: ContextualStoredAsJsonSerializer.java    From Rosetta with Apache License 2.0 4 votes vote down vote up
protected void serializeAsBytes(T value, JsonGenerator generator, SerializerProvider provider, StdSerializer<byte[]> delegate) throws IOException {
  delegate.serialize(serializeToBytes(value, getMapper(generator), provider), generator, provider);
}
 
Example #13
Source File: ConstantBinarySerializer.java    From Rosetta with Apache License 2.0 4 votes vote down vote up
private static StdSerializer<byte[]> newInstance(String className) throws Exception {
  return (StdSerializer<byte[]>) Class.forName(className).newInstance();
}
 
Example #14
Source File: StoredAsJsonBinarySerializer.java    From Rosetta with Apache License 2.0 4 votes vote down vote up
private static StdSerializer<byte[]> newInstance(String className) throws Exception {
  return (StdSerializer<byte[]>) Class.forName(className).newInstance();
}
 
Example #15
Source File: JacksonUtil.java    From steady with Apache License 2.0 2 votes vote down vote up
/**
 * Serializes the given object to JSON, thereby using the given {@link StdSerializer}s and no view {@link Class}.
 *
 * @param _object a {@link java.lang.Object} object.
 * @param _custom_serializers a {@link java.util.Map} object.
 * @return a {@link java.lang.String} object.
 */
public static String asJsonString(final Object _object, final Map<Class<?>, StdSerializer<?>> _custom_serializers) {
	return JacksonUtil.asJsonString(_object, _custom_serializers, null);
}
 
Example #16
Source File: JacksonUtil.java    From steady with Apache License 2.0 2 votes vote down vote up
/**
 * Transforms the given {@link Object} into an instance of the given {@link Class}.
 * 
 * This is done by serialiazing the object into JSON with {@link #asJsonString(Object, Map, Class)},
 * followed by deserializing with {@link #asObject(String, Class).
 *  
 * @param _from
 * @param _to
 * @return
 */
public static Object fromTo(final Object _from, final Map<Class<?>, StdSerializer<?>> _custom_serializers, final Class _view, final Class<?> _to) {
	final String json = JacksonUtil.asJsonString(_from, _custom_serializers, _view);
	return JacksonUtil.asObject(json, _to);
}