下面列出了com.fasterxml.jackson.databind.ser.std.StdSerializer#com.fasterxml.jackson.databind.deser.std.StdDeserializer 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
@SuppressWarnings("unchecked")
public JsonDeserializer createDeserializer() {
return new StdDeserializer<Enum>(Enum.class) {
@Override
public Enum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
CustomProtobufParser pp = (CustomProtobufParser) p;
Class<Enum> enumType = ProtobufParserUtil.getEnumClassOfCurrentField(pp.getCurrentMessage(), pp.getCurrentField());
switch (protobufConfig.getEnumMode()) {
case ByOrdinal:
// minus 1 to match .net
int ordinal = p.getIntValue() - 1;
return enumType.getEnumConstants()[ordinal];
case ByValue:
return createEnumFromValue(enumType, p.getIntValue());
}
throw new RuntimeException("unknown enum mode " + protobufConfig.getEnumMode());
}
};
}
TestModule()
{
addSerializer(Interval.class, ToStringSerializer.instance);
addDeserializer(
Interval.class, new StdDeserializer<Interval>(Interval.class)
{
@Override
public Interval deserialize(
JsonParser jsonParser, DeserializationContext deserializationContext
) throws IOException, JsonProcessingException
{
return new Interval(jsonParser.getText());
}
}
);
}
private TypeSpec.Builder createSerialisationForDateTime(ObjectPluginContext objectPluginContext) {
ClassName returnType = ClassName.get(Date.class);
TypeSpec.Builder builder = TypeSpec.classBuilder("TimestampDeserializer")
.addModifiers(Modifier.PUBLIC)
.superclass(ParameterizedTypeName.get(ClassName.get(StdDeserializer.class), returnType))
.addField(FieldSpec.builder(StdDateFormat.class, "DATE_PARSER", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).initializer("new $T()", StdDateFormat.class).build())
.addMethod(
MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
.addCode("super($T.class);", returnType).build()
).addModifiers(Modifier.PUBLIC);
MethodSpec.Builder deserialize = MethodSpec.methodBuilder("deserialize")
.addModifiers(Modifier.PUBLIC)
.addParameter(ParameterSpec.builder(ClassName.get(JsonParser.class), "jsonParser").build())
.addParameter(ParameterSpec.builder(ClassName.get(DeserializationContext.class), "jsonContext").build())
.addException(IOException.class)
.addException(JsonProcessingException.class)
.returns(returnType)
.addCode(
CodeBlock.builder().beginControlFlow("try").add(
CodeBlock.builder()
.addStatement("$T mapper = new $T()", ObjectMapper.class, ObjectMapper.class)
.addStatement("$T dateString = mapper.readValue(jsonParser, String.class)", String.class)
.addStatement("Date date = DATE_PARSER.parse(dateString)", SimpleDateFormat.class)
.addStatement("return date").build()
).add("} catch ($T e) {", ParseException.class).addStatement("throw new $T(e)", IOException.class).endControlFlow().build()
);
builder.addMethod(deserialize.build());
objectPluginContext.createSupportClass(builder);
return builder;
}
@Override
public JsonDeserializer<BigInteger> createDeserializer() {
return new StdDeserializer<BigInteger>(BigInteger.class) {
@Override
public BigInteger deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
// longValue's bits are same as ulong
long longValue = p.getLongValue();
// dump bits and parse it as ulong, effectively parse it as ulong
return new BigInteger(Long.toHexString(longValue), 16);
}
};
}
protected Deserializer(StdDeserializer<?> src) {
super(src);
}
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);
}
@Override
public void runConversion(int numberOfAttributes, int lengthOfAttribute) {
int assignmentsTotal, progress = 0;
assignmentsConverted = submissionsConverted = submissionsFailed = assignmentsFailed = 0;
SimpleModule module = new SimpleModule().addDeserializer(String.class, new StdDeserializer<String>(String.class) {
@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
String str = StringDeserializer.instance.deserialize(p, ctxt);
if (StringUtils.isBlank(str)) return null;
return str;
}
});
// woodstox xml parser defaults we don't allow values smaller than the default
if (numberOfAttributes < ReaderConfig.DEFAULT_MAX_ATTRIBUTES_PER_ELEMENT) numberOfAttributes = ReaderConfig.DEFAULT_MAX_ATTRIBUTES_PER_ELEMENT;
if (lengthOfAttribute < ReaderConfig.DEFAULT_MAX_ATTRIBUTE_LENGTH) lengthOfAttribute = ReaderConfig.DEFAULT_MAX_ATTRIBUTE_LENGTH;
log.info("<===== Assignments conversion xml parser limits: number of attributes={}, attribute size={} =====>", numberOfAttributes, lengthOfAttribute);
XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
xmlInputFactory.setProperty(WstxInputProperties.P_MAX_ATTRIBUTES_PER_ELEMENT, numberOfAttributes);
xmlInputFactory.setProperty(WstxInputProperties.P_MAX_ATTRIBUTE_SIZE, lengthOfAttribute);
xmlMapper = new XmlMapper(xmlInputFactory);
xmlMapper.registerModule(new Jdk8Module());
xmlMapper.registerModule(module);
String configValue = "org.sakaiproject.assignment.api.model.Assignment,org.sakaiproject.assignment.api.model.AssignmentSubmission";
String currentValue = serverConfigurationService.getConfig(AssignableUUIDGenerator.HIBERNATE_ASSIGNABLE_ID_CLASSES, null);
if (StringUtils.isNotBlank(currentValue)) {
configValue = configValue + "," + currentValue;
}
ServerConfigurationService.ConfigItem configItem = BasicConfigItem.makeConfigItem(
AssignableUUIDGenerator.HIBERNATE_ASSIGNABLE_ID_CLASSES,
configValue,
AssignmentConversionServiceImpl.class.getName(),
true);
serverConfigurationService.registerConfigItem(configItem);
List<String> preAssignments = dataProvider.fetchAssignmentsToConvert();
List<String> postAssignments = assignmentRepository.findAllAssignmentIds();
List<String> convertAssignments = new ArrayList<>(preAssignments);
convertAssignments.removeAll(postAssignments);
assignmentsTotal = convertAssignments.size();
log.info("<===== Assignments pre 12 [{}] and post 12 [{}] to convert {} =====>", preAssignments.size(), postAssignments.size(), assignmentsTotal);
for (String assignmentId : convertAssignments) {
try {
convert(assignmentId);
} catch (Exception e) {
log.warn("Assignment conversion exception for {}", assignmentId, e);
}
int percent = new Double(((assignmentsConverted + assignmentsFailed) / (double) assignmentsTotal) * 100).intValue();
if (progress != percent) {
progress = percent;
log.info("<===== Assignments conversion completed {}% =====>", percent);
}
}
configItem = BasicConfigItem.makeConfigItem(
AssignableUUIDGenerator.HIBERNATE_ASSIGNABLE_ID_CLASSES,
StringUtils.trimToEmpty(currentValue),
AssignmentConversionServiceImpl.class.getName());
serverConfigurationService.registerConfigItem(configItem);
log.info("<===== Assignments converted {} =====>", assignmentsConverted);
log.info("<===== Submissions converted {} =====>", submissionsConverted);
log.info("<===== Assignments that failed to be converted {} =====>", assignmentsFailed);
log.info("<===== Submissions that failed to be converted {} =====>", submissionsFailed);
}
@Override
public void runConversion(int numberOfAttributes, int lengthOfAttribute) {
int assignmentsTotal, progress = 0;
assignmentsConverted = submissionsConverted = submissionsFailed = assignmentsFailed = 0;
SimpleModule module = new SimpleModule().addDeserializer(String.class, new StdDeserializer<String>(String.class) {
@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
String str = StringDeserializer.instance.deserialize(p, ctxt);
if (StringUtils.isBlank(str)) return null;
return str;
}
});
// woodstox xml parser defaults we don't allow values smaller than the default
if (numberOfAttributes < ReaderConfig.DEFAULT_MAX_ATTRIBUTES_PER_ELEMENT) numberOfAttributes = ReaderConfig.DEFAULT_MAX_ATTRIBUTES_PER_ELEMENT;
if (lengthOfAttribute < ReaderConfig.DEFAULT_MAX_ATTRIBUTE_LENGTH) lengthOfAttribute = ReaderConfig.DEFAULT_MAX_ATTRIBUTE_LENGTH;
log.info("<===== Assignments conversion xml parser limits: number of attributes={}, attribute size={} =====>", numberOfAttributes, lengthOfAttribute);
XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
xmlInputFactory.setProperty(WstxInputProperties.P_MAX_ATTRIBUTES_PER_ELEMENT, numberOfAttributes);
xmlInputFactory.setProperty(WstxInputProperties.P_MAX_ATTRIBUTE_SIZE, lengthOfAttribute);
xmlMapper = new XmlMapper(xmlInputFactory);
xmlMapper.registerModule(new Jdk8Module());
xmlMapper.registerModule(module);
String configValue = "org.sakaiproject.assignment.api.model.Assignment,org.sakaiproject.assignment.api.model.AssignmentSubmission";
String currentValue = serverConfigurationService.getConfig(AssignableUUIDGenerator.HIBERNATE_ASSIGNABLE_ID_CLASSES, null);
if (StringUtils.isNotBlank(currentValue)) {
configValue = configValue + "," + currentValue;
}
ServerConfigurationService.ConfigItem configItem = BasicConfigItem.makeConfigItem(
AssignableUUIDGenerator.HIBERNATE_ASSIGNABLE_ID_CLASSES,
configValue,
AssignmentConversionServiceImpl.class.getName(),
true);
serverConfigurationService.registerConfigItem(configItem);
List<String> preAssignments = dataProvider.fetchAssignmentsToConvert();
List<String> postAssignments = assignmentRepository.findAllAssignmentIds();
List<String> convertAssignments = new ArrayList<>(preAssignments);
convertAssignments.removeAll(postAssignments);
assignmentsTotal = convertAssignments.size();
log.info("<===== Assignments pre 12 [{}] and post 12 [{}] to convert {} =====>", preAssignments.size(), postAssignments.size(), assignmentsTotal);
for (String assignmentId : convertAssignments) {
try {
convert(assignmentId);
} catch (Exception e) {
log.warn("Assignment conversion exception for {}", assignmentId, e);
}
int percent = new Double(((assignmentsConverted + assignmentsFailed) / (double) assignmentsTotal) * 100).intValue();
if (progress != percent) {
progress = percent;
log.info("<===== Assignments conversion completed {}% =====>", percent);
}
}
configItem = BasicConfigItem.makeConfigItem(
AssignableUUIDGenerator.HIBERNATE_ASSIGNABLE_ID_CLASSES,
StringUtils.trimToEmpty(currentValue),
AssignmentConversionServiceImpl.class.getName());
serverConfigurationService.registerConfigItem(configItem);
log.info("<===== Assignments converted {} =====>", assignmentsConverted);
log.info("<===== Submissions converted {} =====>", submissionsConverted);
log.info("<===== Assignments that failed to be converted {} =====>", assignmentsFailed);
log.info("<===== Submissions that failed to be converted {} =====>", submissionsFailed);
}