Example usage for com.fasterxml.jackson.databind ObjectMapper writeValueAsString

List of usage examples for com.fasterxml.jackson.databind ObjectMapper writeValueAsString

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper writeValueAsString.

Prototype

@SuppressWarnings("resource")
public String writeValueAsString(Object value) throws JsonProcessingException 

Source Link

Document

Method that can be used to serialize any Java value as a String.

Usage

From source file:EntityProvider.java

private String toJSON(E entity) {
    String json = null;//from w ww.  j a  va  2 s.c  om
    ObjectifyJacksonModule ojm = new ObjectifyJacksonModule();
    ObjectMapper mapper = new ObjectMapper();

    mapper.registerModule(ojm);

    try {
        json = mapper.writeValueAsString(entity);
    } catch (JsonProcessingException jpe) {
        jpe.printStackTrace();
    }

    logger.info("Serializing '" + json + "'.");
    return json;
}

From source file:com.fhc25.percepcion.osiris.mapviewer.common.data.RequestConfiguration.java

public void setBodyObject(Object object) {

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    ObjectMapper mapper = new ObjectMapper();

    try {/*from   w  ww. j  a v  a2  s.c  o m*/
        this.body = mapper.writeValueAsString(object);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:info.archinnov.achilles.type.CounterBuilderTest.java

@Test
public void should_be_able_to_serialize_and_deserialize_null_counter() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    Counter counter = new TestCounter();

    String serialized = mapper.writeValueAsString(counter);
    assertThat(serialized).isEqualTo("\"\"");
    serialized = mapper.writeValueAsString(null);
    assertThat(serialized).isEqualTo("null");

    Counter deserialized = mapper.readValue("null", Counter.class);
    assertThat(deserialized).isNull();/* ww  w  .j ava2  s  .  c o m*/

}

From source file:com.theoryinpractise.coffeescript.CoffeeScriptCompiler.java

public CompileResult compile(String coffeeScriptSource, String sourceName, boolean bare, SourceMap map,
        boolean header, boolean literate) {
    Context context = Context.enter();
    try {//from   ww  w .  jav a2  s .  co m
        Scriptable compileScope = context.newObject(coffeeScript);
        compileScope.setParentScope(coffeeScript);
        compileScope.put("coffeeScript", compileScope, coffeeScriptSource);
        try {
            boolean useMap = map != SourceMap.NONE;
            String options = String.format(
                    "{bare: %s, sourceMap: %s, literate: %s, header: %s, filename: '%s'}", bare, useMap,
                    literate, header, sourceName);
            Object result = context.evaluateString(compileScope,
                    String.format("compile(coffeeScript, %s);", options), sourceName, 0, null);

            if (map == SourceMap.NONE) {
                return new CompileResult((String) result, null);
            } else {

                NativeObject nativeObject = (NativeObject) result;
                String js = nativeObject.get("js").toString();
                String sourceMap;
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    sourceMap = objectMapper.writeValueAsString(nativeObject.get("v3SourceMap"));
                } catch (Exception e) {
                    sourceMap = null;
                }

                return new CompileResult(js, sourceMap);
            }

        } catch (JavaScriptException e) {
            throw new CoffeeScriptException(e.getMessage(), e);
        }
    } finally {
        Context.exit();
    }
}

From source file:io.cortical.retina.core.ClassifyTest.java

/**
 * {@link io.cortical.services.TextRetinaApiImpl#getKeywords(String)} test method.
 *
 * @throws io.cortical.services.api.client.ApiException : should never be thrown
 *//*from   ww w  .  ja  v a 2  s  . c om*/
@Test
public void testCreateCategoryFilter() throws ApiException {
    List<String> pos = Arrays.asList(
            "Shoe with a lining to help keep your feet dry and comfortable on wet terrain.",
            "running shoes providing protective cushioning.");
    List<String> neg = Arrays.asList("The most comfortable socks for your feet.",
            "6 feet USB cable basic white");

    Sample sample = new Sample();
    sample.addAllPositive(pos.toArray(new String[pos.size()]));
    sample.addAllNegative(neg.toArray(new String[neg.size()]));

    String json = null;
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        json = mapper.writeValueAsString(sample);
    } catch (Exception e) {
        e.printStackTrace();
    }

    when(classifyApi.createCategoryFilter(eq("12"), eq(json), eq("en_associative"))).thenReturn(cf);
    CategoryFilter result = classify.createCategoryFilter("12", pos, neg);
    assertTrue(result.getCategoryName().equals("12"));
    assertTrue(result.getPositions().length == 3);
}

From source file:org.venice.piazza.servicecontroller.messaging.handlers.SearchServiceHandler.java

/**
 * /*from   ww w .j  av  a 2 s .  c om*/
 * @param criteria
 *            to search. field and regex expression
 * @return a String of ResourceMetadata items that match the search
 */
public ResponseEntity<String> handle(SearchCriteria criteria) {
    ResponseEntity<String> responseEntity;
    String result;
    if (criteria != null) {
        coreLogger.log("About to search using criteria" + criteria, Severity.INFORMATIONAL);

        List<Service> results = accessor.search(criteria);
        if (results.isEmpty()) {
            coreLogger.log("No results were returned searching for field " + criteria.getField()
                    + " and search criteria " + criteria.getPattern(), Severity.INFORMATIONAL);

            responseEntity = new ResponseEntity<>("No results were returned searching for field",
                    HttpStatus.NO_CONTENT);
        } else {
            ObjectMapper mapper = makeObjectMapper();
            try {
                result = mapper.writeValueAsString(results);
                responseEntity = new ResponseEntity<>(result, HttpStatus.OK);
            } catch (JsonProcessingException jpe) {
                // This should never happen, but still have to catch it
                LOGGER.error("There was a problem generating the Json response", jpe);
                coreLogger.log("There was a problem generating the Json response", Severity.ERROR);
                responseEntity = new ResponseEntity<>("Could not search for services", HttpStatus.NOT_FOUND);
            }
        }
    } else
        responseEntity = new ResponseEntity<>("No criteria was specified", HttpStatus.NO_CONTENT);

    return responseEntity;
}

From source file:io.fineo.drill.exec.store.dynamo.physical.DynamoScanBatchCreator.java

@Override
public CloseableRecordBatch getBatch(FragmentContext context, DynamoSubScan subScan, List<RecordBatch> children)
        throws ExecutionSetupException {
    Preconditions.checkArgument(children.isEmpty());

    List<RecordReader> readers = Lists.newArrayList();
    List<SchemaPath> columns = subScan.getColumns();
    ClientProperties clientProps = subScan.getClient();
    ClientConfiguration client = clientProps.getConfiguration();
    AWSCredentialsProvider credentials = subScan.getCredentials();
    DynamoEndpoint endpoint = subScan.getEndpoint();
    DynamoTableDefinition table = subScan.getTable();
    DynamoKeyMapper key = null;//from  w  w  w  .  jav a 2s .c  o  m
    if (table.getKeyMapper() != null) {
        DynamoKeyMapperSpec spec = table.getKeyMapper();
        Map<String, Object> args = spec.getArgs();
        ObjectMapper mapper = new ObjectMapper();
        try {
            String argString = mapper.writeValueAsString(args);
            InjectableValues inject = new InjectableValues.Std().addValue(DynamoKeyMapperSpec.class, spec);
            key = mapper.setInjectableValues(inject).readValue(argString, DynamoKeyMapper.class);
        } catch (IOException e) {
            throw new ExecutionSetupException(e);
        }
    }

    for (DynamoSubReadSpec scanSpec : subScan.getSpecs()) {
        try {
            DynamoRecordReader reader;
            if (scanSpec instanceof DynamoSubGetSpec) {
                reader = new DynamoGetRecordReader(credentials, client, endpoint, (DynamoSubGetSpec) scanSpec,
                        columns, clientProps.getConsistentRead(), table);
            } else if (scanSpec instanceof DynamoSubQuerySpec) {
                reader = new DynamoQueryRecordReader(credentials, client, endpoint,
                        (DynamoSubQuerySpec) scanSpec, columns, clientProps.getConsistentRead(),
                        subScan.getScanProps(), table);
            } else {
                reader = new DynamoScanRecordReader(credentials, client, endpoint, (DynamoSubScanSpec) scanSpec,
                        columns, clientProps.getConsistentRead(), subScan.getScanProps(), table);
            }
            if (key != null) {
                reader.setKeyMapper(key);
            }
            readers.add(reader);
        } catch (Exception e1) {
            throw new ExecutionSetupException(e1);
        }
    }
    return new ScanBatch(subScan, context, readers.iterator());
}

From source file:com.linecorp.bot.model.message.imagemap.URIImagemapActionTest.java

@Test
public void getLinkUri() throws Exception {
    URIImagemapAction imageMapAction = new URIImagemapAction("http://example.com",
            new ImagemapArea(1, 2, 3, 4));

    ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule())
            .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
    String s = objectMapper.writeValueAsString(imageMapAction);
    assertThat(s).contains("\"type\":\"uri\"");
}

From source file:demo.ServiceLocationTests.java

@Test
public void jsonWithId() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ServiceLocation input = new ServiceLocation(52, 0);
    input.setId("102");
    ServiceLocation value = mapper.readValue(mapper.writeValueAsString(input), ServiceLocation.class);
    assertEquals(52, value.getLatitude(), 0.01);
    assertEquals("102", value.getId());
}

From source file:org.jddd.jackson.SimpleValueObjectSerializerModifierUnitTests.java

@Test
public void automaticallyUnwrapsSinglePropertyValueObjects() throws Exception {

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new DddModule());

    EmailAddress email = EmailAddress.of("foo@bar.com");
    String result = mapper.writeValueAsString(new Wrapper(email));

    System.out.println(result);//from  w w w. j  av a 2  s  .c o m

    assertThat(JsonPath.<String>read(result, "$.email")).isEqualTo("foo@bar.com");
}