List of usage examples for com.fasterxml.jackson.databind.module SimpleModule addSerializer
public <T> SimpleModule addSerializer(Class<? extends T> type, JsonSerializer<T> ser)
From source file:models.OntoProcessor.java
/** * Initialize the Jackson Mapper with personalize serializer * for every class in the ontology domain model. *///from w w w . j a v a 2 s . co m protected void initializeMapper() { mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(Category.class, new CategorySerializer()); module.addSerializer(ImpactType.class, new TypeSerializer()); module.addSerializer(ElementaryFlowType.class, new TypeSerializer()); module.addSerializer(Group.class, new GroupSerializer()); module.addSerializer(SourceRelation.class, new SourceRelationSerializer()); module.addSerializer(DerivedRelation.class, new DerivedRelationSerializer()); module.addSerializer(com.mycsense.carbondb.domain.Process.class, new ProcessSerializer()); module.addSerializer(Coefficient.class, new CoefficientSerializer()); module.addSerializer(Reference.class, new ReferenceSerializer()); mapper.registerModule(module); }
From source file:it.eng.spagobi.engines.network.bean.JSONNetwork.java
/** * JSON serializer for this object// w ww .j a v a2 s . c o m * @return the network serialized * @throws SerializationException */ @JsonIgnore public String getNetworkAsString() throws SerializationException { ObjectMapper mapper = new ObjectMapper(); String s = ""; try { SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1, 0, 0, null)); simpleModule.addSerializer(Node.class, new NodeJSONSerializer()); simpleModule.addSerializer(Edge.class, new EdgeJSONSerializer()); mapper.registerModule(simpleModule); s = mapper.writeValueAsString((JSONNetwork) this); } catch (Exception e) { throw new SerializationException("Error serializing the network", e); } s = StringEscapeUtils.unescapeJavaScript(s); return s; }
From source file:de.fraunhofer.iosb.ilt.sta.serialize.EntityFormatter.java
public EntityFormatter(List<Property> selectedProperties) { mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); mapper.setPropertyNamingStrategy(new EntitySetCamelCaseNamingStrategy()); mapper.addMixIn(Datastream.class, DatastreamMixIn.class); mapper.addMixIn(MultiDatastream.class, MultiDatastreamMixIn.class); mapper.addMixIn(FeatureOfInterest.class, FeatureOfInterestMixIn.class); mapper.addMixIn(HistoricalLocation.class, HistoricalLocationMixIn.class); mapper.addMixIn(Location.class, LocationMixIn.class); mapper.addMixIn(Observation.class, ObservationMixIn.class); mapper.addMixIn(ObservedProperty.class, ObservedPropertyMixIn.class); mapper.addMixIn(Sensor.class, SensorMixIn.class); mapper.addMixIn(Thing.class, ThingMixIn.class); mapper.addMixIn(UnitOfMeasurement.class, UnitOfMeasurementMixIn.class); mapper.addMixIn(EntitySetResult.class, EntitySetResultMixIn.class); SimpleModule module = new SimpleModule(); CustomSerializationManager.getInstance().registerSerializer("application/vnd.geo+json", new GeoJsonSerializer()); if (selectedProperties != null && !selectedProperties.isEmpty()) { module.addSerializer(Entity.class, new EntitySerializer( selectedProperties.stream().map(x -> x.getName()).collect(Collectors.toList()))); } else {/*from w w w .j a va 2s.c om*/ module.addSerializer(Entity.class, new EntitySerializer()); } module.addSerializer(EntitySetResult.class, new EntitySetResultSerializer()); module.addSerializer(DataArrayValue.class, new DataArrayValueSerializer()); module.addSerializer(DataArrayResult.class, new DataArrayResultSerializer()); mapper.registerModule(module); }
From source file:com.zenesis.qx.remote.ProxyObjectMapper.java
/** * Constructor//from ww w. j ava2 s .c o m * @param tracker * @param indent whether to indent JSON * @param rootDir root directory to serialise all File's as relative to */ public ProxyObjectMapper(ProxySessionTracker tracker, boolean indent, File rootDir) { super(); this.tracker = tracker; SimpleModule module = new SimpleModule("ProxyObjectMapper", Version.unknownVersion()); module.addSerializer(Proxied.class, new ProxiedSerializer()); module.addDeserializer(Proxied.class, new ProxiedDeserializer()); module.addSerializer(Date.class, new DateSerializer()); module.addSerializer(String.class, new StringSerializer()); module.addSerializer(Enum.class, new EnumSerializer()); module.addSerializer(File.class, new FileSerializer(rootDir)); module.addDeserializer(File.class, new FileDeserializer(rootDir)); module.addSerializer(Map.class, new MapSerializer()); registerModule(module); }
From source file:org.pentaho.pdi.engine.serializers.DataEventSerializer.java
public DataEventSerializer() { super(DataEvent.class); SimpleModule module = new SimpleModule(); module.addSerializer(DataEvent.class, new JsonSerializer<DataEvent>() { @Override//from w w w . j a v a2s. c om public void serialize(DataEvent dataEvent, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject(); Rows rows = (Rows) dataEvent.getData(); jsonGenerator.writeStringField("model-id", dataEvent.getSource().getId()); jsonGenerator.writeStringField("type", rows.getType().toString()); jsonGenerator.writeStringField("state", rows.getState().toString()); jsonGenerator.writeArrayFieldStart("rows"); for (Row row : rows) { jsonGenerator.writeStartObject(); jsonGenerator.writeArrayFieldStart("names"); for (String name : row.getColumnNames()) { jsonGenerator.writeString(name); } jsonGenerator.writeEndArray(); jsonGenerator.writeArrayFieldStart("objects"); for (Object obj : row.getObjects().get()) { jsonGenerator.writeStartObject(); if (obj == null) { jsonGenerator.writeStringField("type", "Null"); jsonGenerator.writeEndObject(); continue; } switch (obj.getClass().getSimpleName()) { case "String": jsonGenerator.writeStringField("type", "String"); jsonGenerator.writeStringField("obj", obj.toString()); break; case "Date": jsonGenerator.writeStringField("type", "Date"); jsonGenerator.writeStringField("obj", DATE_TIME_INSTANCE.format((Date) obj)); break; case "Integer": jsonGenerator.writeStringField("type", "Integer"); jsonGenerator.writeNumberField("obj", (Integer) obj); break; case "Long": jsonGenerator.writeStringField("type", "Long"); jsonGenerator.writeNumberField("obj", (Long) obj); break; case "Double": jsonGenerator.writeStringField("type", "Double"); jsonGenerator.writeNumberField("obj", (Double) obj); break; case "BigDecimal": jsonGenerator.writeStringField("type", "BigDecimal"); jsonGenerator.writeStringField("obj", obj.toString()); break; case "Boolean": jsonGenerator.writeStringField("type", "Boolean"); jsonGenerator.writeBooleanField("obj", (Boolean) obj); break; case "byte[]": jsonGenerator.writeStringField("type", "byte[]"); jsonGenerator.writeStringField("obj", new String(((byte[]) obj), "UTF-8")); break; default: if (obj instanceof Serializable) { jsonGenerator.writeStringField("type", "Object"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(obj); objectOutputStream.close(); outputStream.close(); byte[] bytes = outputStream.toByteArray(); jsonGenerator.writeStringField("obj", Base64.encodeBase64String(bytes)); } } jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); jsonGenerator.writeEndObject(); } }); module.addDeserializer(DataEvent.class, new StdNodeBasedDeserializer<DataEvent>(DataEvent.class) { @Override public DataEvent convert(JsonNode jsonNode, DeserializationContext deserializationContext) throws IOException { Rows.TYPE type = Rows.TYPE.valueOf(jsonNode.get("type").asText()); Rows.STATE state = Rows.STATE.valueOf(jsonNode.get("state").asText()); List<Row> rows = new ArrayList<>(); JsonNode json_rows = jsonNode.get("rows"); for (JsonNode row : json_rows) { List<Class> types = new ArrayList<>(); List<String> names = new ArrayList<>(); for (JsonNode name : row.get("names")) { names.add(name.asText()); } List<Object> objects = new ArrayList<>(); for (JsonNode obj : row.get("objects")) { JsonNode t = obj.get("type"); JsonNode rawObject = obj.get("obj"); Object object = null; String objType = t.asText(); switch (objType) { case "Null": types.add(Void.class); break; case "String": types.add(String.class); object = rawObject.asText(); break; case "Integer": types.add(Integer.class); object = rawObject.asInt(); break; case "Long": types.add(Long.class); object = rawObject.asLong(); break; case "Date": types.add(Date.class); try { object = DATE_TIME_INSTANCE.parse(rawObject.asText()); } catch (ParseException e) { e.printStackTrace(); } break; case "Double": types.add(Double.class); object = rawObject.asDouble(); break; case "BigDecimal": types.add(BigDecimal.class); object = new BigDecimal(rawObject.asText()); break; case "Boolean": types.add(Boolean.class); object = rawObject.asBoolean(); break; case "byte[]": types.add(byte[].class); object = rawObject.asText().getBytes("UTF-8"); break; case "Object": try { types.add(Object.class); object = new ObjectInputStream( new ByteArrayInputStream(Base64.decodeBase64(rawObject.asText()))) .readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } break; } objects.add(object); } Row r = new DeserializedRow(names, types, objects); rows.add(r); } Rows rowsObj = new Rows(rows, type, state); return new DataEvent(new RemoteSource(jsonNode.get("model-id").asText()), rowsObj); } }); mapper.registerModule(module); }
From source file:com.basho.riak.client.api.commands.mapreduce.MapReduce.java
/** * Creates the JSON string of the M/R job for submitting to the client * <p/>//from w ww .ja va 2 s. co m * Uses Jackson to write out the JSON string. I'm not very happy with this method, it is a candidate for change. * <p/> * TODO re-evaluate this method, look for something smaller and more elegant. * * @return a String of JSON * @throws RiakException if, for some reason, we can't create a JSON string. */ String writeSpec() throws RiakException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { JsonGenerator jg = new JsonFactory().createGenerator(out, JsonEncoding.UTF8); ObjectMapper objectMapper = new ObjectMapper(); SimpleModule specModule = new SimpleModule("SpecModule", Version.unknownVersion()); specModule.addSerializer(LinkPhase.class, new LinkPhaseSerializer()); specModule.addSerializer(FunctionPhase.class, new FunctionPhaseSerializer()); specModule.addSerializer(BucketInput.class, new BucketInputSerializer()); specModule.addSerializer(SearchInput.class, new SearchInputSerializer()); specModule.addSerializer(BucketKeyInput.class, new BucketKeyInputSerializer()); specModule.addSerializer(IndexInput.class, new IndexInputSerializer()); objectMapper.registerModule(specModule); jg.setCodec(objectMapper); List<MapReducePhase> phases = spec.getPhases(); phases.get(phases.size() - 1).setKeep(true); jg.writeObject(spec); jg.flush(); return out.toString("UTF8"); } catch (IOException e) { throw new RiakException(e); } }
From source file:es.logongas.ix3.web.json.impl.JsonWriterImplEntityJackson.java
public JsonWriterImplEntityJackson() { objectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(java.util.Date.class, new DateSerializer()); objectMapper.registerModule(module); }
From source file:org.zalando.problem.ProblemModule.java
@Override public void setupModule(final SetupContext context) { final SimpleModule module = new SimpleModule(); module.setMixInAnnotation(Exceptional.class, stacktraces ? ExceptionalWithStacktraceMixin.class : ExceptionalMixin.class); module.setMixInAnnotation(DefaultProblem.class, DefaultProblemMixIn.class); module.setMixInAnnotation(Problem.class, ProblemMixIn.class); module.addSerializer(StatusType.class, new StatusTypeSerializer()); module.addDeserializer(StatusType.class, new StatusTypeDeserializer(statuses)); module.setupModule(context);// w ww . j av a 2 s . c o m }
From source file:com.netflix.bdp.inviso.history.TraceService.java
/** * Returns a json object representing the job history. * * @param jobId/* w w w.j a v a 2 s . c o m*/ * @param path Use the given path as opposed to the history locator * @param summary Return just the top level details of the job * @param counters Include counters * @return Json string * @throws Exception */ @Path("load/{jobId}") @GET @Produces("application/json") public String trace(@PathParam("jobId") final String jobId, @QueryParam("path") final String path, @QueryParam("summary") boolean summary, @QueryParam("counters") @DefaultValue("true") boolean counters) throws Exception { Pair<org.apache.hadoop.fs.Path, org.apache.hadoop.fs.Path> historyPath; if (path != null) { historyPath = new ImmutablePair<>(null, new org.apache.hadoop.fs.Path(path)); } else { historyPath = historyLocator.locate(jobId); } if (historyPath == null) { throw new WebApplicationException(404); } TraceJobHistoryLoader loader = new TraceJobHistoryLoader(properties); FileSystem fs = FileSystem.get(historyPath.getRight().toUri(), config); CompressionCodec codec = new CompressionCodecFactory(config).getCodec(historyPath.getRight()); FSDataInputStream fin = fs.open(historyPath.getRight()); if (codec != null) { fin = new FSDataInputStream(new WrappedCompressionInputStream(codec.createInputStream(fin))); } JobHistoryParser parser = new JobHistoryParser(fin); parser.parse(loader); String[] ignore = { "counters" }; ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule("MyModule", new Version(1, 0, 0, null)); //Job JavaType jobMapType = MapLikeType.construct(Job.class, SimpleType.construct(String.class), SimpleType.construct(Object.class)); module.addSerializer(Job.class, MapSerializer.construct(ignore, jobMapType, false, null, null, null, null)); //Task JavaType taskMapType = MapLikeType.construct(Task.class, SimpleType.construct(String.class), SimpleType.construct(Object.class)); module.addSerializer(Task.class, MapSerializer.construct(ignore, taskMapType, false, null, null, null, null)); //Attempt JavaType attemptMapType = MapLikeType.construct(TaskAttempt.class, SimpleType.construct(String.class), SimpleType.construct(Object.class)); module.addSerializer(TaskAttempt.class, MapSerializer.construct(ignore, attemptMapType, false, null, null, null, null)); if (!counters) { mapper.registerModule(module); } if (summary) { loader.getJob().clearTasks(); } return mapper.writeValueAsString(loader.getJob()); }
From source file:io.klerch.alexa.state.model.AlexaStateModel.java
/** * Returns a json with key-value-pairs - one for each AlexaStateSave-annotated field in this model configured to be valid * in the given scope//from www . j a va2s . co m * @param scope The scope a AlexaStateSave-annotated field must have or be part of to be considered in the returned json * @throws AlexaStateException Wraps all inner exceptions and gives you context related to handler and model * @return A json-string with key-value-pairs - one for each AlexaStateSave-annotated field in this model configured to be valid */ public String toJSON(final AlexaScope scope) throws AlexaStateException { // for each scope there is a custom json serializer so initialize the one which corresponds to the given scope final AlexaStateSerializer serializer = AlexaScope.APPLICATION.equals(scope) ? new AlexaAppStateSerializer() : AlexaScope.USER.equals(scope) ? new AlexaUserStateSerializer() : new AlexaSessionStateSerializer(); // associate a mapper with the serializer final ObjectMapper mapper = new ObjectMapper(); final SimpleModule module = new SimpleModule(); module.addSerializer(this.getClass(), serializer); mapper.registerModule(module); try { // serialize model which only contains those fields tagged with the given scope return mapper.writeValueAsString(this); } catch (JsonProcessingException e) { final String error = String.format("Error while serializing model of '%1$s' as Json.", this); log.error(error, e); throw AlexaStateException.create(error).withCause(e).withModel(this).build(); } }