下面列出了怎么用com.fasterxml.jackson.core.Version的API类实例代码及写法,或者点击链接到github查看源代码。
public ObjectifyJacksonModule() {
super( "Objectify", Version.unknownVersion() );
// Objectify Key
addSerializer( Key.class, new KeyStdSerializer() );
addDeserializer( Key.class, new KeyStdDeserializer() );
addKeySerializer( Key.class, new KeyJsonSerializer() );
addKeyDeserializer( Key.class, new KeyStdKeyDeserializer() );
// Objectify Ref
addSerializer( Ref.class, new RefStdSerializer() );
addDeserializer( Ref.class, new RefStdDeserializer() );
addKeySerializer( Ref.class, new RefJsonSerializer() );
addKeyDeserializer( Ref.class, new RefStdKeyDeserializer() );
// Native datastore Key
addSerializer( com.google.appengine.api.datastore.Key.class, new RawKeyStdSerializer() );
addDeserializer( com.google.appengine.api.datastore.Key.class, new RawKeyStdDeserializer() );
addKeySerializer( com.google.appengine.api.datastore.Key.class, new RawKeyJsonSerializer() );
addKeyDeserializer( com.google.appengine.api.datastore.Key.class, new RawKeyStdKeyDeserializer() );
}
public static ObjectMapper newMapper(ManagementContext mgmt) {
ConfigurableSerializerProvider sp = new ConfigurableSerializerProvider();
sp.setUnknownTypeSerializer(new ErrorAndToStringUnknownTypeSerializer());
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializerProvider(sp);
mapper.setVisibilityChecker(new PossiblyStrictPreferringFieldsVisibilityChecker());
SimpleModule mapperModule = new SimpleModule("Brooklyn", new Version(0, 0, 0, "ignored", null, null));
new BidiSerialization.ManagementContextSerialization(mgmt).install(mapperModule);
new BidiSerialization.EntitySerialization(mgmt).install(mapperModule);
new BidiSerialization.LocationSerialization(mgmt).install(mapperModule);
new BidiSerialization.PolicySerialization(mgmt).install(mapperModule);
new BidiSerialization.EnricherSerialization(mgmt).install(mapperModule);
new BidiSerialization.FeedSerialization(mgmt).install(mapperModule);
new BidiSerialization.TaskSerialization(mgmt).install(mapperModule);
new BidiSerialization.ClassLoaderSerialization(mgmt).install(mapperModule);
mapperModule.addSerializer(Duration.class, new DurationSerializer());
mapperModule.addSerializer(new MultimapSerializer());
mapper.registerModule(mapperModule);
return mapper;
}
/**
* Will attempt to load the maven version for the given groupId and
* artifactId. Maven puts a pom.properties file in
* META-INF/maven/groupId/artifactId, containing the groupId,
* artifactId and version of the library.
*
* @param cl the ClassLoader to load the pom.properties file from
* @param groupId the groupId of the library
* @param artifactId the artifactId of the library
* @return The version
*
* @deprecated Since 2.6: functionality not used by any official Jackson component, should be
* moved out if anyone needs it
*/
@SuppressWarnings("resource")
@Deprecated // since 2.6
public static Version mavenVersionFor(ClassLoader cl, String groupId, String artifactId)
{
InputStream pomProperties = cl.getResourceAsStream("META-INF/maven/"
+ groupId.replaceAll("\\.", "/")+ "/" + artifactId + "/pom.properties");
if (pomProperties != null) {
try {
Properties props = new Properties();
props.load(pomProperties);
String versionStr = props.getProperty("version");
String pomPropertiesArtifactId = props.getProperty("artifactId");
String pomPropertiesGroupId = props.getProperty("groupId");
return parseVersion(versionStr, pomPropertiesGroupId, pomPropertiesArtifactId);
} catch (IOException e) {
// Ignore
} finally {
_close(pomProperties);
}
}
return Version.unknownVersion();
}
private void addTekuMappers() {
SimpleModule module = new SimpleModule("TekuJson", new Version(1, 0, 0, null, null, null));
module.addSerializer(Bitlist.class, new BitlistSerializer());
module.addDeserializer(Bitlist.class, new BitlistDeserializer());
module.addDeserializer(Bitvector.class, new BitvectorDeserializer());
module.addSerializer(Bitvector.class, new BitvectorSerializer());
module.addSerializer(BLSPubKey.class, new BLSPubKeySerializer());
module.addDeserializer(BLSPubKey.class, new BLSPubKeyDeserializer());
module.addDeserializer(BLSSignature.class, new BLSSignatureDeserializer());
module.addSerializer(BLSSignature.class, new BLSSignatureSerializer());
module.addDeserializer(Bytes32.class, new Bytes32Deserializer());
module.addDeserializer(Bytes4.class, new Bytes4Deserializer());
module.addSerializer(Bytes4.class, new Bytes4Serializer());
module.addDeserializer(Bytes.class, new BytesDeserializer());
module.addSerializer(Bytes.class, new BytesSerializer());
module.addDeserializer(UnsignedLong.class, new UnsignedLongDeserializer());
module.addSerializer(UnsignedLong.class, new UnsignedLongSerializer());
objectMapper.registerModule(module).writer(new DefaultPrettyPrinter());
}
public static List<AppStatus> deserializeAppStatus(String platformStatus) {
try {
if (platformStatus != null) {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(AppStatus.class, AppStatusMixin.class);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
SimpleModule module = new SimpleModule("CustomModel", Version.unknownVersion());
SimpleAbstractTypeResolver resolver = new SimpleAbstractTypeResolver();
resolver.addMapping(AppInstanceStatus.class, AppInstanceStatusImpl.class);
module.setAbstractTypes(resolver);
mapper.registerModule(module);
TypeReference<List<AppStatus>> typeRef = new TypeReference<List<AppStatus>>() {
};
return mapper.readValue(platformStatus, typeRef);
}
return new ArrayList<>();
}
catch (Exception e) {
logger.error("Could not parse Skipper Platform Status JSON [" + platformStatus + "]. " +
"Exception message = " + e.getMessage());
return new ArrayList<>();
}
}
@JsonIgnore
public List<AppStatus> getAppStatusList() {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(AppStatus.class, AppStatusMixin.class);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
SimpleModule module = new SimpleModule("CustomModel", Version.unknownVersion());
SimpleAbstractTypeResolver resolver = new SimpleAbstractTypeResolver();
resolver.addMapping(AppInstanceStatus.class, AppInstanceStatusImpl.class);
module.setAbstractTypes(resolver);
mapper.registerModule(module);
TypeReference<List<AppStatus>> typeRef = new TypeReference<List<AppStatus>>() {
};
if (this.platformStatus != null) {
return mapper.readValue(this.platformStatus, typeRef);
}
return new ArrayList<AppStatus>();
}
catch (Exception e) {
throw new IllegalArgumentException("Could not parse Skipper Platfrom Status JSON:" + platformStatus, e);
}
}
public DynamicConfigApiJsonModule() {
super(DynamicConfigApiJsonModule.class.getSimpleName(), new Version(1, 0, 0, null, null, null));
registerSubtypes(
new NamedType(ClusterActivationNomadChange.class, "ClusterActivationNomadChange"),
new NamedType(MultiSettingNomadChange.class, "MultiSettingNomadChange"),
new NamedType(NodeAdditionNomadChange.class, "NodeAdditionNomadChange"),
new NamedType(ClusterActivationNomadChange.class, "ClusterActivationNomadChange"),
new NamedType(NodeRemovalNomadChange.class, "NodeRemovalNomadChange"),
new NamedType(SettingNomadChange.class, "SettingNomadChange"));
setMixInAnnotation(NodeNomadChange.class, NodeNomadChangeMixin.class);
setMixInAnnotation(Applicability.class, ApplicabilityMixin.class);
setMixInAnnotation(ClusterActivationNomadChange.class, ClusterActivationNomadChangeMixin.class);
setMixInAnnotation(MultiSettingNomadChange.class, MultiSettingNomadChangeMixin.class);
setMixInAnnotation(NodeAdditionNomadChange.class, NodeAdditionNomadChangeMixin.class);
setMixInAnnotation(NodeRemovalNomadChange.class, NodeRemovalNomadChangeMixin.class);
setMixInAnnotation(SettingNomadChange.class, SettingNomadChangeMixin.class);
}
public NomadJsonModule() {
super(NomadJsonModule.class.getSimpleName(), new Version(1, 0, 0, null, null, null));
setMixInAnnotation(NomadChange.class, NomadChangeMixin.class);
setMixInAnnotation(MutativeMessage.class, MutativeMessageMixin.class);
setMixInAnnotation(AcceptRejectResponse.class, AcceptRejectResponseMixin.class);
setMixInAnnotation(ChangeDetails.class, ChangeDetailsMixin.class);
setMixInAnnotation(CommitMessage.class, CommitMessageMixin.class);
setMixInAnnotation(DiscoverResponse.class, DiscoverResponseMixin.class);
setMixInAnnotation(PrepareMessage.class, PrepareMessageMixin.class);
setMixInAnnotation(RollbackMessage.class, RollbackMessageMixin.class);
setMixInAnnotation(TakeoverMessage.class, TakeoverMessageMixin.class);
setMixInAnnotation(ChangeRequest.class, ChangeRequestMixin.class);
setMixInAnnotation(NomadChangeInfo.class, NomadChangeInfoMixin.class);
}
public static JSONArray serializeGraph(Query query) throws Exception {
QueryGraph graph = query.getQueryGraph();
if (graph != null) {
logger.debug("The graph of the query is not null" + graph.toString());
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1, 0, 0, null));
simpleModule.addSerializer(Relationship.class, new RelationJSONSerializerForAnalysisState());
mapper.registerModule(simpleModule);
String serialized = mapper.writeValueAsString(graph.getConnections());
logger.debug("The serialization of the graph is " + serialized);
JSONArray array = new JSONArray(serialized);
return array;
} else {
logger.debug("The graph of the query is null");
return new JSONArray();
}
}
public static Module module(final CodecRegistry registry) {
Preconditions.checkNotNull(registry, "registry");
return new Module() {
@Override
public String getModuleName() {
return JacksonCodecs.class.getSimpleName();
}
@Override
public Version version() {
return Version.unknownVersion();
}
@Override
public void setupModule(SetupContext context) {
context.addSerializers(serializers(registry));
}
};
}
@Override
protected void additionalProperties(Properties properties) {
ObjectMapper objectMapper = new ObjectMapper().findAndRegisterModules();
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1, 0, 0, null, null, null));
simpleModule.addSerializer(new MoneySerializer());
objectMapper.registerModule(simpleModule);
JsonBinaryType jsonBinaryType = new JsonBinaryType(objectMapper, Location.class);
properties.put("hibernate.type_contributors",
(TypeContributorList) () -> Collections.singletonList(
(typeContributions, serviceRegistry) ->
typeContributions.contributeType(
jsonBinaryType, "location"
)
)
);
}
private static SimpleModule getWriteLongAsStringModule() {
JsonSerializer<Long> longSerializer = new JsonSerializer<Long>() {
@Override
public void serialize(Long value, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeString(value.toString());
}
};
SimpleModule writeLongAsStringModule = new SimpleModule("writeLongAsStringModule",
new Version(1, 0, 0, null, null, null));
writeLongAsStringModule.addSerializer(Long.TYPE, longSerializer); // long (primitive)
writeLongAsStringModule.addSerializer(Long.class, longSerializer); // Long (class)
return writeLongAsStringModule;
}
/**
* Creates Katharsis Jackson module with all required serializers
*
* @param resourceRegistry initialized registry with all of the required resources
* @param isClient is katharsis client
* @return {@link com.fasterxml.jackson.databind.Module} with custom serializers
*/
public SimpleModule build(ResourceRegistry resourceRegistry, boolean isClient) {
SimpleModule simpleModule = new SimpleModule(JSON_API_MODULE_NAME,
new Version(1, 0, 0, null, null, null));
simpleModule.addSerializer(new ErrorDataSerializer());
simpleModule.addDeserializer(ErrorData.class, new ErrorDataDeserializer());
return simpleModule;
}
public JtsModule3D(GeometryFactory geometryFactory) {
super("JtsModule3D", new Version(1, 0, 0, null,"com.bedatadriven","jackson-datatype-jts"));
addSerializer(Geometry.class, new GeometrySerializer());
GenericGeometryParser genericGeometryParser = new GenericGeometryParser(geometryFactory);
addDeserializer(Geometry.class, new GeometryDeserializer<Geometry>(genericGeometryParser));
addDeserializer(Point.class, new GeometryDeserializer<Point>(new PointParser(geometryFactory)));
addDeserializer(MultiPoint.class, new GeometryDeserializer<MultiPoint>(new MultiPointParser(geometryFactory)));
addDeserializer(LineString.class, new GeometryDeserializer<LineString>(new LineStringParser(geometryFactory)));
addDeserializer(MultiLineString.class, new GeometryDeserializer<MultiLineString>(new MultiLineStringParser(geometryFactory)));
addDeserializer(Polygon.class, new GeometryDeserializer<Polygon>(new PolygonParser(geometryFactory)));
addDeserializer(MultiPolygon.class, new GeometryDeserializer<MultiPolygon>(new MultiPolygonParser(geometryFactory)));
addDeserializer(GeometryCollection.class, new GeometryDeserializer<GeometryCollection>(new GeometryCollectionParser(geometryFactory, genericGeometryParser)));
}
AvroObjectModule() {
super(
AvroObject.class.getSimpleName(),
Version.unknownVersion(),
Map.of(AvroObject.class, new AvroObjectDeserializer()),
List.of(new AvroObjectSerializer())
);
}
public void testLongSerOverideWithAfterburner() throws Exception
{
String json = afterburnerMapperBuilder()
.addModule(new SimpleModule("module", Version.unknownVersion())
.addSerializer(Long.class, new MyLongSerializer())
.addSerializer(Long.TYPE, new MyLongSerializer()))
.build()
.writeValueAsString(new SimpleLongBean());
assertEquals(aposToQuotes("{'value':-999}"), json);
}
public SentinelJsonConfiguration() {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
ApiPredicateItemDeserializer deserializer = new ApiPredicateItemDeserializer();
deserializer.registerApiPredicateItem("pattern",
ApiPathPredicateItem.class);
deserializer.registerApiPredicateItem("items",
ApiPredicateGroupItem.class);
SimpleModule module = new SimpleModule(
"PolymorphicApiPredicateItemDeserializerModule",
new Version(1, 0, 0, null));
module.addDeserializer(ApiPredicateItem.class, deserializer);
objectMapper.registerModule(module);
}
@Before
public void setup() {
mapper = new ObjectMapper();
mapper.registerModule(new SimpleModule("EventSourcing", new Version(1, 0, 0, null, "eventsourcing",
"eventsourcing")).
addSerializer(InteractionContext.class, new InteractionContextSerializer()).
addDeserializer(InteractionContext.class, new InteractionContextDeserializer()).setMixInAnnotation(
Event.class, JacksonEvent.class));
eventStorage = new FileEventStorage(mapper);
}
/**
* Creates Crnk Jackson module with all required serializers.<br />
* Adds the {@link LinksInformationSerializer} if <code>serializeLinksAsObjects</code> is set to <code>true</code>.
*
* @param serializeLinksAsObjects flag which decides whether the {@link LinksInformationSerializer} should be added as
* additional serializer or not.
* @return {@link com.fasterxml.jackson.databind.Module} with custom serializers
*/
public static SimpleModule createJacksonModule(boolean serializeLinksAsObjects) {
SimpleModule simpleModule = new SimpleModule(JSON_API_JACKSON_MODULE_NAME,
new Version(1, 0, 0, null, null, null));
simpleModule.addSerializer(new ErrorDataSerializer());
simpleModule.addDeserializer(ErrorData.class, new ErrorDataDeserializer());
simpleModule.addSerializer(new LinksInformationSerializer(serializeLinksAsObjects));
return simpleModule;
}
public InetJsonModule() {
super(InetJsonModule.class.getSimpleName(), new Version(1, 0, 0, null, null, null));
addSerializer(InetSocketAddress.class, ToStringSerializer.instance);
addDeserializer(InetSocketAddress.class, new FromStringDeserializer<InetSocketAddress>(InetSocketAddress.class) {
private static final long serialVersionUID = 1L;
@Override
protected InetSocketAddress _deserialize(String value, DeserializationContext ctxt) {
return InetSocketAddressConverter.getInetSocketAddress(value);
}
});
}
/**
* Constructors that should only be used for non-reusable
* convenience modules used by app code: "real" modules should
* use actual name and version number information.
*/
public SimpleModule() {
// can't chain when making reference to 'this'
// note: generate different name for direct instantiation, sub-classing
_name = (getClass() == SimpleModule.class) ?
"SimpleModule-"+System.identityHashCode(this)
: getClass().getName();
_version = Version.unknownVersion();
}
/**
* Method used by <code>PackageVersion</code> classes to decode version injected by Maven build.
*/
public static Version parseVersion(String s, String groupId, String artifactId)
{
if (s != null && (s = s.trim()).length() > 0) {
String[] parts = V_SEP.split(s);
return new Version(parseVersionPart(parts[0]),
(parts.length > 1) ? parseVersionPart(parts[1]) : 0,
(parts.length > 2) ? parseVersionPart(parts[2]) : 0,
(parts.length > 3) ? parts[3] : null,
groupId, artifactId);
}
return Version.unknownVersion();
}
private void assertVersion(Versioned vers)
{
Version v = vers.version();
assertFalse("Should find version information (got "+v+")", v.isUnknownVersion());
Version exp = PackageVersion.VERSION;
assertEquals(exp.toFullString(), v.toFullString());
assertEquals(exp, v);
}
/**
* Method used by <code>PackageVersion</code> classes to decode version injected by Maven build.
*/
public static Version parseVersion(String s, String groupId, String artifactId)
{
if (s != null && (s = s.trim()).length() > 0) {
String[] parts = V_SEP.split(s);
return new Version(parseVersionPart(parts[0]),
(parts.length > 1) ? parseVersionPart(parts[1]) : 0,
(parts.length > 2) ? parseVersionPart(parts[2]) : 0,
(parts.length > 3) ? parts[3] : null,
groupId, artifactId);
}
return Version.unknownVersion();
}
/**
* No-args Constructor.
*/
public LinkIdModule() {
super(NAME, new Version(1, 0, 0, null, "org.interledger", "link-id"));
addSerializer(LinkId.class, new LinkIdSerializer());
addDeserializer(LinkId.class, new LinkIdDeserializer());
}
public JtsModule(GeometryFactory geometryFactory) {
super("JtsModule", new Version(1, 0, 0, null,"com.bedatadriven","jackson-datatype-jts"));
addSerializer(Geometry.class, new GeometrySerializer());
GenericGeometryParser genericGeometryParser = new GenericGeometryParser(geometryFactory);
addDeserializer(Geometry.class, new GeometryDeserializer<Geometry>(genericGeometryParser));
addDeserializer(Point.class, new GeometryDeserializer<Point>(new PointParser(geometryFactory)));
addDeserializer(MultiPoint.class, new GeometryDeserializer<MultiPoint>(new MultiPointParser(geometryFactory)));
addDeserializer(LineString.class, new GeometryDeserializer<LineString>(new LineStringParser(geometryFactory)));
addDeserializer(MultiLineString.class, new GeometryDeserializer<MultiLineString>(new MultiLineStringParser(geometryFactory)));
addDeserializer(Polygon.class, new GeometryDeserializer<Polygon>(new PolygonParser(geometryFactory)));
addDeserializer(MultiPolygon.class, new GeometryDeserializer<MultiPolygon>(new MultiPolygonParser(geometryFactory)));
addDeserializer(GeometryCollection.class, new GeometryDeserializer<GeometryCollection>(new GeometryCollectionParser(geometryFactory, genericGeometryParser)));
}
/**
* No-args Constructor.
*/
public SharedSecretModule() {
super(
NAME,
new Version(1, 0, 0, null, "org.interledger", "jackson-datatype-shared-secret")
);
addSerializer(SharedSecret.class, SharedSecretSerializer.INSTANCE);
addDeserializer(SharedSecret.class, SharedSecretDeserializer.INSTANCE);
}
/**
* No-args Constructor.
*/
public InterledgerAddressModule() {
super(
NAME,
new Version(1, 0, 0, null, "org.interledger", "jackson-datatype-interledger-address")
);
addSerializer(InterledgerAddress.class, InterledgerAddressSerializer.INSTANCE);
addDeserializer(InterledgerAddress.class, InterledgerAddressDeserializer.INSTANCE);
}
private static SimpleModule getWriteDateAsStringModule() {
JsonSerializer<Date> dateSerializer = new JsonSerializer<Date>() {
@Override
public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeString(new com.google.api.client.util.DateTime(value).toStringRfc3339());
}
};
SimpleModule writeDateAsStringModule = new SimpleModule("writeDateAsStringModule",
new Version(1, 0, 0, null, null, null));
writeDateAsStringModule.addSerializer(Date.class, dateSerializer);
return writeDateAsStringModule;
}
public static void configureMapper(ObjectMapper mapper) {
mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
mapper.registerSubtypes(DeckConfig.class);
SimpleModule module = new SimpleModule("", new Version(0, 5, 0, "", "com.cardshifter", "cardshifter"));
module.setMixInAnnotation(DeckConfig.class, MixinDeckConfig.class);
module.setMixInAnnotation(Message.class, MixinMessage.class);
module.setMixInAnnotation(CardInfoMessage.class, MixinCardInfoMessage.class);
module.setMixInAnnotation(PlayerConfigMessage.class, MixinPlayerConfigMessage.class);
module.setMixInAnnotation(ErrorMessage.class, MixinErrorMessage.class);
mapper.registerModule(module);
}