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:com.linecorp.armeria.server.docs.DocServiceTest.java

@Test
public void testOk() throws Exception {
    final Map<Class<?>, Iterable<EndpointInfo>> serviceMap = new HashMap<>();
    serviceMap.put(HelloService.class, Collections
            .singletonList(EndpointInfo.of("*", "/", "hello", THRIFT_BINARY, SerializationFormat.ofThrift())));
    serviceMap.put(SleepService.class, Collections
            .singletonList(EndpointInfo.of("*", "/", "sleep", THRIFT_BINARY, SerializationFormat.ofThrift())));
    serviceMap.put(FooService.class, Collections
            .singletonList(EndpointInfo.of("*", "/foo", "", THRIFT_COMPACT, EnumSet.of(THRIFT_COMPACT))));
    serviceMap.put(Cassandra.class,
            Arrays.asList(EndpointInfo.of("*", "/cassandra", "", THRIFT_BINARY, EnumSet.of(THRIFT_BINARY)),
                    EndpointInfo.of("*", "/cassandra/debug", "", THRIFT_TEXT, EnumSet.of(THRIFT_TEXT))));
    serviceMap.put(Hbase.class, Collections
            .singletonList(EndpointInfo.of("*", "/hbase", "", THRIFT_BINARY, SerializationFormat.ofThrift())));
    serviceMap.put(OnewayHelloService.class, Collections
            .singletonList(EndpointInfo.of("*", "/oneway", "", THRIFT_BINARY, SerializationFormat.ofThrift())));

    final ObjectMapper mapper = new ObjectMapper();
    final String expectedJson = mapper.writeValueAsString(Specification.forServiceClasses(serviceMap,
            ImmutableMap.of(hello_args.class, SAMPLE_HELLO), SAMPLE_HTTP_HEADERS));

    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final HttpGet req = new HttpGet(specificationUri());

        try (CloseableHttpResponse res = hc.execute(req)) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
            String responseJson = EntityUtils.toString(res.getEntity());

            // Convert to Map for order-insensitive comparison.
            Map<?, ?> actual = mapper.readValue(responseJson, Map.class);
            Map<?, ?> expected = mapper.readValue(expectedJson, Map.class);
            assertThat(actual).isEqualTo(expected);
        }/*w  ww  . j  a  v a  2  s .com*/
    }
}

From source file:com.vmware.bdd.usermgmt.job.CfgUserMgmtOnMgmtVMExecutor.java

private void writeJsonFile(UserMgmtServer userMgmtServer, File file,
        SssdConfigurationGenerator sssdLdapConstantMappings) {
    SssdLdapParam sssdLdapParam = new SssdLdapParam();

    //initialize by template
    sssdLdapParam.sssd_ldap.putAll(sssdLdapConstantMappings.get(userMgmtServer.getType()));

    //override values.
    sssdLdapParam.sssd_ldap.put("ldap_group_search_base", userMgmtServer.getBaseGroupDn());
    sssdLdapParam.sssd_ldap.put("ldap_user_search_base", userMgmtServer.getBaseUserDn());
    sssdLdapParam.sssd_ldap.put("ldap_uri", userMgmtServer.getPrimaryUrl());
    sssdLdapParam.sssd_ldap.put("ldap_default_bind_dn", userMgmtServer.getUserName());
    sssdLdapParam.sssd_ldap.put("ldap_default_authtok", userMgmtServer.getPassword());
    sssdLdapParam.sssd_ldap.put("ldap_access_filter", "memberOf=" + userMgmtServer.getMgmtVMUserGroupDn());

    sssdLdapParam.run_list.add("recipe[sssd_ldap]");

    try {//  ww  w.  ja  va  2  s. c om
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(sssdLdapParam);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("writing Configuration manifest in json " + json + " to file " + file);
        }

        try (BufferedWriter out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));) {
            out.write(json);
        }
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage() + "\n failed to write enable_LDAP spec file " + file);
        throw new UserMgmtExecException("WRITE_CFG_LDAP_JSON_FAIL", ex);
    }
}

From source file:org.springframework.cloud.dataflow.server.support.StepExecutionJacksonMixInTests.java

/**
 * Assert that without using the {@link ExecutionContextJacksonMixIn} Jackson does not
 * render the Step Execution Context correctly (Missing values).
 *
 * @throws JsonProcessingException if a Json generation error occurs.
 *//*from w  w  w.j a  v  a 2s.c o m*/
@Test(expected = JsonMappingException.class)
public void testSerializationOfSingleStepExecutionWithoutMixin() throws JsonProcessingException {

    final ObjectMapper objectMapper = new ObjectMapper();

    final StepExecution stepExecution = getStepExecution();
    final String result = objectMapper.writeValueAsString(stepExecution);

    assertThat(result, containsString("\"executionContext\":{\"dirty\":true,\"empty\":false}"));
}

From source file:app.service.internal.JsonBooleanTest.java

@Test
public void booleanTest() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    BooleanField field = new BooleanField();
    field.setOn(true);//from  w  w w .  ja v a2 s  . c  o  m
    field.setHasDone(true);

    String json = mapper.writeValueAsString(field);
    logger.info(json);
    Assert.assertTrue("key contain 'hasDone'", json.contains("hasDone"));
    Assert.assertTrue("key contain 'isOn", json.contains("isOn"));

    BooleanField item = mapper.readValue(json, BooleanField.class);
    Assert.assertTrue("item.hasDone", item.hasDone);
    Assert.assertTrue("item.isOn", item.isOn);
}

From source file:com.examples.abelanav2.grpcclient.CacheStore.java

/**
 * Stores everything in the SharedPreferences for caching.
 *///  w w  w .j a va  2  s.  com
public void backup() {
    SharedPreferences settings = mContext.getSharedPreferences(AndroidConstants.SHARED_PREFS_PHOTOS, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.clear();
    ObjectMapper mapper = new ObjectMapper();
    try {
        editor.putString("photoList", mapper.writeValueAsString(mPhotoLists));
        editor.putString("photoListNextPage", mapper.writeValueAsString(mPhotoListsNextPage));
    } catch (JsonProcessingException e) {
        Log.e("PhotoAdapter", e.getMessage());
    }
    editor.apply();
}

From source file:io.liveoak.security.policy.drools.integration.DroolsPolicyConfigResource.java

@Override
public Map<String, ?> properties(RequestContext ctx) throws Exception {
    ObjectMapper om = ObjectMapperFactory.create();
    // TODO: performance as Object is converted couple of times into various formats...
    String str = om.writeValueAsString(this.droolsPolicyConfig);
    ObjectNode objectNode = om.readValue(str, ObjectNode.class);
    ResourceState resourceState = ConversionUtils.convert(objectNode);
    List<ResourceState> childResourceStates = (List<ResourceState>) resourceState.getProperty(RULES_PROPERTY);
    List<Resource> childResources = ResourceConversionUtils.convertList(childResourceStates, this);
    resourceState.putProperty(RULES_PROPERTY, childResources);
    return new DefaultResourceState(resourceState).propertyMap();
}

From source file:org.o3project.ocnrm.lib.JSONParser.java

public <K> String convertToJson(K target, String seqNo) throws JSONException, JsonProcessingException {
    logger.info(seqNo + "\t" + "convertToJson() Start");
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    String jsonArray = mapper.writeValueAsString(target);
    logger.info(seqNo + "\t" + "convertToJson() End");
    return jsonArray;
}

From source file:io.fabric8.example.stddev.http.StdDevProcessorTest.java

@Test
public void testProcess() throws Exception {
    RandomGenerator rg = new JDKRandomGenerator();
    double[] array = new double[10];
    ObjectMapper objectMapper = new ObjectMapper();
    for (int i = 0; i < array.length; i++) {
        array[i] = rg.nextDouble();//from  ww  w . j  a  v a2  s.c o m
    }
    String body = objectMapper.writeValueAsString(array);
    SummaryStatistics summaryStatistics = new SummaryStatistics();
    List<Double> list = new ObjectMapper().readValue(body, List.class);
    for (Double value : list) {
        summaryStatistics.addValue(value);
    }
    String stdDev = Double.toString(summaryStatistics.getStandardDeviation());

    resultEndpoint.expectedBodiesReceived(stdDev);

    template.sendBody(body);

    resultEndpoint.assertIsSatisfied();
}

From source file:com.pymegest.applicationserver.api.SessionController.java

@RequestMapping(value = { "/Session" }, method = RequestMethod.GET)
public void read(HttpServletRequest httpServletRequest, HttpServletResponse response) {

    try {//from w ww .j  a  v  a 2  s  .  c om

        Integer idUsuario = (Integer) httpServletRequest.getSession(true).getAttribute("idUduario");

        Usuario usuario = usuarioDAO.read(idUsuario);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json; chaset=UTF-8");

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(usuario);
        response.getWriter().println(json);

    } catch (Exception ex) {

        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }
}

From source file:io.fabric8.example.variance.http.VarianceProcessorTest.java

@Test
public void testProcess() throws Exception {
    RandomGenerator rg = new JDKRandomGenerator();
    double[] array = new double[10];
    ObjectMapper objectMapper = new ObjectMapper();
    for (int i = 0; i < array.length; i++) {
        array[i] = rg.nextDouble();// www. ja  v  a 2  s.  c  o  m
    }
    String body = objectMapper.writeValueAsString(array);
    String expectedBody = "0.0";
    SummaryStatistics summaryStatistics = new SummaryStatistics();
    List<Double> list = new ObjectMapper().readValue(body, List.class);
    for (Double value : list) {
        summaryStatistics.addValue(value);
    }
    String variance = Double.toString(summaryStatistics.getVariance());

    resultEndpoint.expectedBodiesReceived(variance);

    template.sendBody(body);

    resultEndpoint.assertIsSatisfied();
}