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:org.esupportail.nfctagdroid.logback.HttpAppender.java

private void doPost(final String event) {

    LogBean nfctagdroidlog = new LogBean();
    nfctagdroidlog.setNumeroId(LocalStorage.getValue("numeroId"));
    nfctagdroidlog.setErrorLevel(event.split("]")[0].replace("[", ""));
    nfctagdroidlog.setErrorReport(event.split("]")[1].trim());
    ObjectMapper mapper = new ObjectMapper();
    String jsonInString = null;//from  w  w w .j  a v a  2s  .c  o  m
    try {
        jsonInString = mapper.writeValueAsString(nfctagdroidlog);
    } catch (JsonProcessingException e) {
        throw new NfcTagDroidException("", e);
    }
    final String[] params = new String[2];
    params[0] = getEndpoint();
    params[1] = jsonInString;
    LogHttpRequestAsync task = new LogHttpRequestAsync();
    try {
        task.execute(params).get(time, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        throw new NfcTagDroidException("Time out Log", e);
    } catch (InterruptedException e) {
        throw new NfcTagDroidException("InterruptedException", e);
    } catch (ExecutionException e) {
        throw new NfcTagDroidException("ExecutionException", e);
    }

}

From source file:org.isaacphysics.labs.chemistry.checker.RunParser.java

public String toJSON(String input, String result) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode node1 = mapper.createObjectNode();
    node1.put("result", result);
    node1.put("input", input);
    return mapper.writeValueAsString(node1);
}

From source file:com.surfs.storage.block.service.impl.BlockUserServiceImpl.java

@SuppressWarnings("unchecked")
@Override/*from  w  ww  . j  a v  a 2  s.  c om*/
public String addRemoteBlockUserTarget(Map<String, Object> map) throws Exception {
    String ip = map.get("currentIp").toString();
    List<Map<String, String>> blockUserTargetList = (List<Map<String, String>>) map.get("blockUserTargetList");
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(blockUserTargetList);
    try {
        String url = HttpUtils.getUrl(ip, Constant.REST_SERVICE_PORT, BlockConstant.POOL_SERVICE_PATH,
                BlockConstant.EXPORT_SERVICE_ADDBLOCKUSER_NAME);
        return HttpUtils.invokeHttpForGet(url, json);
    } catch (IOException e) {
        LogFactory.error(e.getMessage());
    }
    return null;
}

From source file:fr.assoba.open.sel.generator.JSONGenerator.java

@Override
public void generate(List<Namespace> namespaces, IO io) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    for (Namespace namespace : namespaces) {
        String output = mapper.writeValueAsString(namespace);
        io.writeFile(namespace.getName() + ".json", output);
    }/*www  .j  ava  2s.  c om*/
}

From source file:com.opsie.opsiecomponent.test.ComponentTest.java

/**
 * Test of initComponentInfo method, of class Component.
 *///w  w w.  ja v a2s.co  m
@Test
public void test_component_init() {
    TaskPanelComponent taskComponent = new TaskPanelComponent();
    componentProcessor.processComponent(taskComponent);
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        String data = objectMapper.writeValueAsString(taskComponent);
        System.out.println("data = " + data);
    } catch (JsonProcessingException ex) {
        Logger.getLogger(ComponentTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.esupportail.nfctagdroid.requestasync.CsnHttpRequestAsync.java

protected String doInBackground(String... params) {

    CsnMessageBean nfcMsg = new CsnMessageBean();
    nfcMsg.setNumeroId(LocalStorage.getValue("numeroId"));
    nfcMsg.setCsn(params[0]);/*ww  w .ja va2 s  .c  o m*/
    ObjectMapper mapper = new ObjectMapper();
    String jsonInString = null;
    try {
        jsonInString = mapper.writeValueAsString(nfcMsg);
        URL url = new URL(NfcTacDroidActivity.ESUP_NFC_TAG_SERVER_URL + "/csn-ws");
        log.info("Will call csn-ws on : " + url);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        conn.connect();
        Writer writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
        writer.write(jsonInString);
        writer.close();
        InputStream inputStream = conn.getInputStream();
        String response = "";
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        while ((line = br.readLine()) != null) {
            response += line;
        }
        conn.disconnect();
        return response;
    } catch (Exception e) {
        throw new NfcTagDroidException(e);
    }
}

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

/**
 * Endpoint for creating a {@link CategoryFilter} from text inputs.
 * /*  www  .j a v  a2s .c o  m*/
 * @param filterName            the name of the category filter
 * @param positiveExamples      list of strings illustrating positive examples.
 * @param negativeExamples      list of strings illustrating negative examples.
 * @return {@link CategoryFilter}
 * @throws ApiException if problem occurs accessing the api
 */
public CategoryFilter createCategoryFilter(String filterName, List<String> positiveExamples,
        List<String> negativeExamples) throws ApiException {
    if (isEmpty(filterName) || positiveExamples == null || positiveExamples.isEmpty()) {
        throw new IllegalArgumentException(NULL_TEXT_MSG);
    }

    Sample sample = makeSample(positiveExamples, negativeExamples);

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

    return this.api.createCategoryFilter(filterName, json, retinaName);
}

From source file:cn.com.esrichina.gcloud.commons.LicenseFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    String url = request.getRequestURI();
    Boolean result = matchExcludePatterns(url);
    if (result) {
        filterChain.doFilter(request, response);
        return;//from   w  w w. ja  v  a2  s .co  m
    }

    if (licenceContext.getIsAuthorized()) {
        doFilter(request, response, filterChain);
    } else {
        response.setContentType("text/json;charset=UTF-8");

        // TODO ajax Json???HTTP?
        PrintWriter writer = response.getWriter();

        RestResponse res = new RestResponse(false, licenceContext.getReason());

        ObjectMapper mapper = new ObjectMapper();
        String json = "";
        try {
            json = mapper.writeValueAsString(res);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        writer.print(json);
        writer.close();
    }
}

From source file:org.o3project.ocnrm.odenos.linklayerizer.LinkLayerizerBoundarySet.java

public String changeBoundariestoJSON() {
    logger.info("changeBoundariestoJSON Start");

    String jsonBoundaries = "";
    try {//from  w w w. j  a  v a  2s . c om
        ObjectMapper mapper = new ObjectMapper();
        jsonBoundaries = mapper.writeValueAsString(linklayerizerBoundaryMap);
        logger.debug("jsonBoundaries:" + jsonBoundaries);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }

    logger.info("changeBoundariestoJSON Endt");
    return jsonBoundaries;
}

From source file:com.netflix.conductor.core.events.TestActionProcessor.java

@Test
public void testNoExpand() throws Exception {
    ParametersUtils pu = new ParametersUtils();

    Map<String, Object> map = new HashMap<>();
    map.put("name", "conductor");
    map.put("version", 2);
    map.put("externalId", "{\"taskRefName\":\"t001\",\"workflowId\":\"w002\"}");

    Map<String, Object> input = new HashMap<>();
    input.put("k1", "${$.externalId}");
    input.put("k4", "${name}");
    input.put("k5", "${version}");

    ObjectMapper om = new ObjectMapper();
    Object jsonObj = om.readValue(om.writeValueAsString(map), Object.class);

    Map<String, Object> replaced = pu.replace(input, jsonObj);
    assertNotNull(replaced);//from   www.ja  v a2  s . co m
    System.out.println("testNoExpand(): " + replaced);

    assertEquals("{\"taskRefName\":\"t001\",\"workflowId\":\"w002\"}", replaced.get("k1"));
    assertEquals("conductor", replaced.get("k4"));
    assertEquals(2, replaced.get("k5"));
}