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.vmware.photon.controller.api.client.resource.TasksApiTest.java

@Test
public void testGetTaskAsync() throws Throwable {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_OK);
    TasksApi tasksApi = new TasksApi(this.restClient);

    tasksApi.getTaskAsync("foo", new FutureCallback<Task>() {
        @Override/*  w  w w.  jav a  2 s.  com*/
        public void onSuccess(@Nullable Task task) {
            assertEquals(task, responseTask);
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
        }
    });
}

From source file:com.vmware.photon.controller.api.client.resource.TasksRestApiTest.java

@Test
public void testGetTaskAsync() throws Throwable {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_OK);
    TasksApi tasksApi = new TasksRestApi(this.restClient);

    tasksApi.getTaskAsync("foo", new FutureCallback<Task>() {
        @Override// ww  w  .j  a  v  a  2 s.  c o m
        public void onSuccess(@Nullable Task task) {
            assertEquals(task, responseTask);
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
        }
    });
}

From source file:com.xeiam.xchange.mtgox.v2.service.streaming.SocketMessageFactory.java

public String subscribeWithChannel(String channel) throws JsonProcessingException {

    HashMap<String, String> map = new HashMap<String, String>(2);
    map.put("op", "mtgox.subscribe");
    map.put("channel", channel);

    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(map);
}

From source file:com.xeiam.xchange.mtgox.v2.service.streaming.SocketMessageFactory.java

public String subscribeWithType(String type) throws JsonProcessingException {

    HashMap<String, String> map = new HashMap<String, String>(2);
    map.put("op", "mtgox.subscribe");
    map.put("type", type);

    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(map);
}

From source file:com.xeiam.xchange.mtgox.v2.service.streaming.SocketMessageFactory.java

public String subscribeWithKey(String key) throws JsonProcessingException {

    HashMap<String, String> map = new HashMap<String, String>(2);
    map.put("op", "mtgox.subscribe");
    map.put("key", key);

    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(map);
}

From source file:uk.ac.surrey.ee.iot.fiware.ngsi9.notify.NotifierAtSubscription.java

@Override
public void run() {

    DiscoveryContextAvailabilityRequest discReq = new DiscoveryContextAvailabilityRequest();
    discReq.getEntityId().addAll(subsReq.getEntityId());
    discReq.getAttribute().addAll(subsReq.getAttribute());
    discReq.getRestriction().setAttributeExpression(subsReq.getRestriction().getAttributeExpression());
    discReq.getRestriction().getOperationScope().addAll(subsReq.getRestriction().getOperationScope());

    Resource02_Discovery discRes = new Resource02_Discovery();
    DiscoveryContextAvailabilityResponse dcar = discRes.parseDiscoveryRequest(discReq);

    NotifyContextAvailabilityRequest ncar = new NotifyContextAvailabilityRequest();
    ncar.getContextRegistrationResponse().addAll(dcar.getContextRegistrationResponse());

    ncar.setSubscriptionId(subsReq.getSubscriptionId());
    //marshal request
    //            NotifyMarshaller nm = new NotifyMarshaller();

    String notifMsg = null;/*from   w w w  .  ja va2 s.  c  o  m*/
    //            try {
    //                notifMsg = nm.marshallRequest(ncar);
    //            } catch (JAXBException ex) {
    //                Logger.getLogger(NotifierAtSubscription.class.getName()).log(Level.SEVERE, null, ex);
    //            }

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    try {
        notifMsg = objectMapper.writeValueAsString(ncar);
    } catch (JsonProcessingException ex) {
        Logger.getLogger(Resource02_Discovery.class.getName()).log(Level.SEVERE, null, ex);
    }

    //notify subscriber
    String callbackUrl = subsReq.getReference();
    ClientResource ngsiClient = new ClientResource(callbackUrl);
    ngsiClient.accept(MediaType.APPLICATION_JSON);
    String payload = notifMsg;
    try {
        ngsiClient.post(payload).write(System.out); //Response is not handled for now
    } catch (IOException ex) {
        Logger.getLogger(NotifierAtSubscription.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.xeiam.xchange.mtgox.v2.service.streaming.SocketMessageFactory.java

public String unsubscribeToChannel(String channel) throws JsonProcessingException {

    HashMap<String, String> map = new HashMap<String, String>(2);
    map.put("op", "unsubscribe");
    map.put("channel", channel);

    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(map);

}

From source file:org.shareok.data.plosdata.PlosApiDataImpl.java

private String getJsonApiResponseByQuery(String query) {
    String jsonData = null;//from  www  .  j  a v a  2  s .  com
    try {
        if (null != query) {
            System.out.println(query);
            //                query = "http://api.plos.org/search?q=author_affiliate%3A%22University%20of%20Oklahoma%22%20AND%20publication_date:[2016-01-01T00:00:00Z+TO+2016-12-31T23:59:59Z]&rows=500&fl=affiliate,doi,author,volume,issue,title,journal,publication_date&api_key=mC8TEAzqwfvDWs4eamFh";
            ApplicationContext context = new ClassPathXmlApplicationContext("htmlRequestContext.xml");
            HttpRequestHandler req = (HttpRequestHandler) context.getBean("httpRequestHandler");
            String response = req.sendGet(query);
            String[] responseInfoArr = response.split("\\n");
            if (null != responseInfoArr[0] && responseInfoArr[0].equals("200")) {
                List<Map<String, String>> articleData = new ArrayList<>();
                String responseDocs = responseInfoArr[1];
                if (!DocumentProcessorUtil.isEmptyString(responseDocs)) {
                    Document doc = DocumentProcessorUtil.loadXMLFromStringContent(responseDocs);
                    NodeList docList = doc.getElementsByTagName("doc");
                    for (int i = 0; i < docList.getLength(); i++) {
                        Element item = (Element) docList.item(i);
                        Map<String, String> tmpMapData = getArticleMapData(item);
                        if (tmpMapData.containsKey("doi")) {
                            articleData.add(tmpMapData);
                        } else {
                            throw new NoDoiDataException(
                                    "Parseing the api response did not get DOI information!");
                        }
                    }
                }
                ObjectMapper mapper = new ObjectMapper();
                jsonData = mapper.writeValueAsString(articleData);
            } else {
                throw new ErrorPlosApiResponseException("Got the response code " + responseInfoArr[0]);
            }
        } else {
            throw new InvalidPlosApiQueryException("The plos api query is null");
        }
    } catch (Exception ex) {
        logger.error(ex);
    }
    return jsonData;
}

From source file:com.base2.kagura.services.camel.routes.ReportsRoutesSystemTest.java

License:asdf

private String buildParameters() throws JsonProcessingException, EncoderException {
    //        List<Map<String, String>> values = new ArrayList<Map<String, String>>();
    Map<String, String> entry = new HashMap<String, String>();
    entry.put("An anonymous string", "asdf");
    //        values.add(entry);
    ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
    String json = mapper.writeValueAsString(entry);
    //        String url = new URLCodec().encode(json); // Rest assured seems to be doing the URI encoding.
    return json;// w w  w .j a v a  2s.  co  m
}

From source file:com.kinvey.business_logic.collection_access.query.AbstractQuery.java

/**
 *
 * @return Query filter as JSon//from  ww w. j  ava2s  .co  m
 */
public String getQueryFilterJson(ObjectMapper mapper) {
    Preconditions.checkNotNull(mapper);
    String jsonResult = "";
    try {
        jsonResult = mapper.writeValueAsString(getQueryFilterMap());
    } catch (Exception ex) {
    }

    // TODO:  Put exception here?

    return jsonResult;
}