Example usage for com.fasterxml.jackson.databind.module SimpleModule addSerializer

List of usage examples for com.fasterxml.jackson.databind.module SimpleModule addSerializer

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.module SimpleModule addSerializer.

Prototype

public <T> SimpleModule addSerializer(Class<? extends T> type, JsonSerializer<T> ser) 

Source Link

Usage

From source file:com.proofpoint.json.ObjectMapperProvider.java

@SuppressWarnings("unchecked")
private <T> void addSerializer(SimpleModule module, Class<?> type, JsonSerializer<?> jsonSerializer) {
    module.addSerializer((Class<? extends T>) type, (JsonSerializer<T>) jsonSerializer);
}

From source file:aptgraph.server.JsonRpcServer.java

/**
 * Start the server, blocking. This method will only return if the server
 * crashed...//from  w w  w  .  ja v  a2  s .co m
 * @throws java.io.IOException if the graph file cannot be read
 * @throws java.lang.ClassNotFoundException if the Graph class is not found
 * @throws java.lang.Exception if the server cannot start...
 */
public final void start() throws IOException, ClassNotFoundException, Exception {

    LOGGER.info("Reading graphs from disk...");
    ObjectInputStream input = new ObjectInputStream(new BufferedInputStream(input_file));
    HashMap<String, LinkedList<Graph<Request>>> user_graphs = (HashMap<String, LinkedList<Graph<Request>>>) input
            .readObject();
    input.close();

    Map.Entry<String, LinkedList<Graph<Request>>> entry_set = user_graphs.entrySet().iterator().next();
    String first_key = entry_set.getKey();
    LOGGER.log(Level.INFO, "Graph has {0} features", user_graphs.get(first_key).size());
    LOGGER.log(Level.INFO, "k-NN Graph : k = {0}", user_graphs.get(first_key).getFirst().getK());
    LOGGER.log(Level.INFO, "Starting JSON-RPC server at http://{0}:{1}",
            new Object[] { config.getServerHost(), config.getServerPort() });

    RequestHandler request_handler = new RequestHandler(user_graphs);

    ObjectMapper object_mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Graph.class, new GraphSerializer());
    module.addSerializer(Domain.class, new DomainSerializer());
    module.addSerializer(Neighbor.class, new NeighborSerializer());
    object_mapper.registerModule(module);

    com.googlecode.jsonrpc4j.JsonRpcServer jsonrpc_server = new com.googlecode.jsonrpc4j.JsonRpcServer(
            object_mapper, request_handler);

    QueuedThreadPool thread_pool = new QueuedThreadPool(config.getMaxThreads(), config.getMinThreads(),
            config.getIdleTimeout(), new ArrayBlockingQueue<Runnable>(config.getMaxPendingRequests()));

    http_server = new org.eclipse.jetty.server.Server(thread_pool);
    //http_server = new org.eclipse.jetty.server.Server();

    ServerConnector http_connector = new ServerConnector(http_server);
    http_connector.setHost(config.getServerHost());
    http_connector.setPort(config.getServerPort());

    http_server.setConnectors(new Connector[] { http_connector });
    http_server.setHandler(new JettyHandler(jsonrpc_server));

    http_server.start();
}

From source file:org.caratarse.auth.services.serialization.JsonSerializationProcessor.java

@Override
protected void initializeModule(SimpleModule module) {
    super.initializeModule(module);

    // Support HalResource (de)serialization.
    module.addDeserializer(HalResource.class, new HalResourceDeserializer());
    module.addSerializer(HalResource.class, new HalResourceSerializer());

}

From source file:it.eng.spagobi.behaviouralmodel.lov.service.GridMetadataContainer.java

/**
 * JSON serializer for this object/*from   ww  w  .  ja  v a 2 s .  c o  m*/
 * @return the network serialized
 * @throws SerializationException
 */
@JsonIgnore
public String toJSONString() throws it.eng.spagobi.commons.serializer.SerializationException {
    ObjectMapper mapper = new ObjectMapper();
    String s = "";
    try {
        SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1, 0, 0, null));
        simpleModule.addSerializer(GridMetadataContainer.class, new GridMetadataContainerJSONSerializer());
        mapper.registerModule(simpleModule);
        s = mapper.writeValueAsString((GridMetadataContainer) this);

    } catch (Exception e) {

        throw new org.apache.commons.lang.SerializationException("Error serializing the network", e);
    }
    s = StringEscapeUtils.unescapeJavaScript(s);
    return s;
}

From source file:com.netflix.suro.jackson.DefaultObjectMapper.java

@Inject
public DefaultObjectMapper(final Injector injector, Set<TypeHolder> crossInjectable) {
    SimpleModule serializerModule = new SimpleModule("SuroServer default serializers");
    serializerModule.addSerializer(ByteOrder.class, ToStringSerializer.instance);
    serializerModule.addDeserializer(ByteOrder.class, new JsonDeserializer<ByteOrder>() {
        @Override/*from w  ww  . j  av a 2s. c o  m*/
        public ByteOrder deserialize(JsonParser jp, DeserializationContext ctxt)
                throws IOException, JsonProcessingException {
            if (ByteOrder.BIG_ENDIAN.toString().equals(jp.getText())) {
                return ByteOrder.BIG_ENDIAN;
            }
            return ByteOrder.LITTLE_ENDIAN;
        }
    });
    registerModule(serializerModule);
    registerModule(new GuavaModule());

    if (injector != null) {
        setInjectableValues(new InjectableValues() {
            @Override
            public Object findInjectableValue(Object valueId, DeserializationContext ctxt,
                    BeanProperty forProperty, Object beanInstance) {
                LOG.info("Looking for " + valueId);
                try {
                    return injector.getInstance(
                            Key.get(forProperty.getType().getRawClass(), Names.named((String) valueId)));
                } catch (Exception e) {
                    try {
                        return injector.getInstance(forProperty.getType().getRawClass());
                    } catch (Exception ex) {
                        LOG.info("No implementation found, returning null");
                    }
                    return null;
                }
            }
        });
    }

    configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    configure(MapperFeature.AUTO_DETECT_CREATORS, false);
    configure(MapperFeature.AUTO_DETECT_FIELDS, false);
    configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
    configure(MapperFeature.AUTO_DETECT_SETTERS, false);
    configure(SerializationFeature.INDENT_OUTPUT, false);

    if (crossInjectable != null) {
        for (TypeHolder entry : crossInjectable) {
            LOG.info("Registering subtype : " + entry.getName() + " -> "
                    + entry.getRawType().getCanonicalName());
            registerSubtypes(new NamedType(entry.getRawType(), entry.getName()));
        }
    }
}

From source file:reactor.js.core.json.NashornJacksonJsonPathProvider.java

public NashornJacksonJsonPathProvider() {
    mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    SimpleModule mod = new SimpleModule();
    mod.addSerializer(JSObject.class, new JSObjectSerializer());
    mod.addDeserializer(JSObject.class, new JSObjectDeserializer());
    mapper.registerModule(mod);// w w w.j  a  v a2s.com
}

From source file:nl.ortecfinance.opal.jacksonweb.IncomePlanningSimulationRequestTest.java

@Test
public void testDoubleSerializer() throws IOException {
    IncomePlanningSimulationRequest req = new IncomePlanningSimulationRequest();

    req.setMyPrimitiveDouble(3.4);//  w  w w .  j  a  v  a 2  s .c  om
    req.setMyObjectDouble(Double.parseDouble("3.9"));
    final double[] doubleArray = new double[] { 2.1, 2, 2 };

    req.setMyPrimitiveDoubleArray(doubleArray);

    double[][] my2DimArray = new double[2][2];
    my2DimArray[0] = new double[] { 2.333333, 2.2555555 };
    my2DimArray[1] = new double[] { 8.1, 8.3 };

    System.out.println("doubleArray:" + doubleArray);
    System.out.println("my2DimArray:" + my2DimArray);

    req.setMyPrimitiveDouble2DimArray(my2DimArray);

    Double[] myObjectDoubleArray = { Double.parseDouble("4.3"), Double.parseDouble("4.5") };
    req.setMyObjectDoubleArray(myObjectDoubleArray);

    SimpleModule module = new SimpleModule();
    module.addSerializer(Double.class, new MyDoubleSerializer());
    module.addSerializer(double.class, new MyDoubleSerializer());
    module.addSerializer(Double[].class, new MyDoubleArraySerializer());
    module.addSerializer(double[].class, new MyPrimitiveDoubleArraySerializer());
    module.addSerializer(double[][].class, new MyPrimitive2DimDoubleArraySerializer());
    module.addSerializer(double[][].class, new MyPrimitive2DimDoubleArraySerializer());

    ObjectMapper m = new ObjectMapper();
    m.registerModule(module);

    StringWriter sw = new StringWriter();
    m.writeValue(sw, req);
    String json = sw.toString();
    System.out.println("testSerializeDate:" + json);
}

From source file:ijfx.service.ui.ImageJInfoService.java

@AngularMethod(sync = true, description = "Return the list of all widgets", inputDescription = "No input")
public JSObject getModuleList() {
    try {//  w  w w  .j a  v a 2 s  . c om
        ObjectMapper mapper = new ObjectMapper();
        logger.fine("Getting module list");
        SimpleModule simpleModule = new SimpleModule("ModuleSerializer");
        // simpleModule.addSerializer(ModuleItem<?>.class,new ModuleItemSerializer());
        simpleModule.addSerializer(ModuleInfo.class, new ModuleSerializer());
        simpleModule.addSerializer(ModuleItem.class, new ModuleItemSerializer());
        mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.registerModule(simpleModule);

        ArrayNode arrayNode = mapper.createArrayNode();

        moduleService.getModules().forEach(module -> {

            //System.out.println("Adding "+module.getName());
            arrayNode.add(mapper.convertValue(module, JsonNode.class));

        });

        //String json = mapper.writeValueAsString(moduleService.getModules());
        logger.fine("JSON done !");

        return JSONUtils.parseToJSON(appService.getCurrentWebEngine(), arrayNode.toString());
        //return JSONUtils.parseToJSON(appService.getCurrentWebEngine(), json);

    } catch (Exception ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    logger.warning("Returning null");
    return null;
}

From source file:gaffer.serialisation.json.hyperloglogplus.HyperLogLogPlusJsonSerialisationTest.java

@Before
public void before() {
    mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);

    final SimpleModule module = new SimpleModule(
            HyperLogLogPlusJsonConstants.HYPER_LOG_LOG_PLUS_SERIALISER_MODULE_NAME, new Version(1, 0, 0, null));
    module.addSerializer(HyperLogLogPlus.class, new HyperLogLogPlusJsonSerialiser());
    module.addDeserializer(HyperLogLogPlus.class, new HyperLogLogPlusJsonDeserialiser());

    mapper.registerModule(module);/*from  w  w  w.j av  a2  s.c o m*/
}

From source file:com.google.code.ssm.transcoders.JsonTranscoderTest.java

@Test
public void testEncodeAndDecodeRegisterSerializerDirectlyToModule() {
    JsonObjectMapper mapper = new JsonObjectMapper();

    // first add serializer then register module
    SimpleModule module = new SimpleModule("cemo", Version.unknownVersion());
    module.addSerializer(Point.class, new PointSerializer());
    mapper.registerModule(module);//  w  w w  .j a v a  2s  .  co  m

    transcoder = new JsonTranscoder(mapper);

    Point p = new Point(40, 50);

    CachedObject co = transcoder.encode(p);
    assertNotNull(co);
    assertNotNull(co.getData());
    assertEquals("{\"v\":\"40x50\"}", new String(co.getData()));
}