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.orange.ngsi2.model.ErrorTest.java

@Test
public void checkSerialization() throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jdk8Module());

    Error parseError = new Error("400");
    String json = objectMapper.writeValueAsString(parseError);
    assertTrue(json.contains("error"));
    assertFalse(json.contains("description"));
    assertFalse(json.contains("affectedItems"));
}

From source file:org.mayocat.accounts.store.jdbi.DBITenantStore.java

private String convertConfigurationToJSON(TenantConfiguration configuration) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(configuration);
}

From source file:com.netsteadfast.greenstep.bsc.esb.router.ApiRouteBuilder.java

@Override
public void configure() throws Exception {
    this.from("servlet:///api").process(new Processor() {

        @Override/*from   w w w.  j  a  v a  2s .  c o  m*/
        public void process(Exchange exchange) throws Exception {
            String format = StringUtils.defaultString(exchange.getIn().getHeader("format", String.class)).trim()
                    .toLowerCase();
            String visionOid = StringUtils.defaultString(exchange.getIn().getHeader("visionOid", String.class))
                    .trim().toLowerCase();
            String startDate = StringUtils.defaultString(exchange.getIn().getHeader("startDate", String.class))
                    .trim().toLowerCase();
            String endDate = StringUtils.defaultString(exchange.getIn().getHeader("endDate", String.class))
                    .trim().toLowerCase();
            String startYearDate = StringUtils
                    .defaultString(exchange.getIn().getHeader("startYearDate", String.class)).trim()
                    .toLowerCase();
            String endYearDate = StringUtils
                    .defaultString(exchange.getIn().getHeader("endYearDate", String.class)).trim()
                    .toLowerCase();
            String frequency = StringUtils.defaultString(exchange.getIn().getHeader("frequency", String.class))
                    .trim().toLowerCase();
            String dataFor = StringUtils.defaultString(exchange.getIn().getHeader("dataFor", String.class))
                    .trim().toLowerCase();
            String measureDataOrganizationOid = StringUtils
                    .defaultString(exchange.getIn().getHeader("measureDataOrganizationOid", String.class))
                    .trim().toLowerCase();
            String measureDataEmployeeOid = StringUtils
                    .defaultString(exchange.getIn().getHeader("measureDataEmployeeOid", String.class)).trim()
                    .toLowerCase();
            String contentFlag = StringUtils
                    .defaultString(exchange.getIn().getHeader("contentFlag", String.class)).trim()
                    .toUpperCase();
            String responseContent = "";
            // ? gsbsc-web applicationContext-STANDARD-CXF.xml
            ApiWebService apiWebService = (ApiWebService) AppContext.getBean("bsc.webservice.ApiWebService");
            BscApiServiceResponse responseObj = apiWebService.getScorecard1(visionOid, startDate, endDate,
                    startYearDate, endYearDate, frequency, dataFor, measureDataOrganizationOid,
                    measureDataEmployeeOid, contentFlag);
            if ("xml".equals(format)) { // xml
                XStream xstream = new XStream();
                xstream.setMode(XStream.NO_REFERENCES);
                xstream.alias("response", BscApiServiceResponse.class);
                responseContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xstream.toXML(responseObj);
            } else { // json
                ObjectMapper mapper = new ObjectMapper();
                responseContent = mapper.writeValueAsString(responseObj);
            }
            exchange.getOut().setBody(responseContent);
        }

    }).to("stream:out");
}

From source file:com.gplus.api.GPlusActivitySerializer.java

@Override
public String serialize(Activity deserialized) {
    ObjectMapper jsonMapper = new ObjectMapper();
    String jsonString = new String();
    try {// ww  w.j  av a  2  s.  c  o m
        jsonString = jsonMapper.writeValueAsString(deserialized);
    } catch (Exception e) {
        LOGGER.error("Exception serializing Activity Object: " + e);
    }
    return jsonString; //To change body of implemented methods use File | Settings | File Templates.
}

From source file:org.imsglobal.lti.lti2.ProductInstanceTest.java

public String getJson(Object o, Boolean prettyPrint) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    if (prettyPrint) {
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
    }//from ww  w.j  av  a 2s. co m
    return mapper.writeValueAsString(o);
}

From source file:org.apache.streams.pig.test.PigConverterTest.java

@Test
public void testPigConverter() throws Exception {

    String[] input = {/*from  w ww.j  a  v  a2s  .  com*/
            "159475541894897679\ttwitter,statuses/user_timeline\t1384499359006\t{\"retweeted_status\":{\"contributors\":null,\"text\":\"The Costa Concordia cruise ship accident could be a disaster for the industry | http://t.co/M9UUNvZi (via @TIMEMoneyland)\",\"geo\":null,\"retweeted\":false,\"in_reply_to_screen_name\":null,\"possibly_sensitive\":false,\"truncated\":false,\"lang\":\"en\",\"entities\":{\"symbols\":[],\"urls\":[{\"expanded_url\":\"http://ti.me/zYyEtD\",\"indices\":[80,100],\"display_url\":\"ti.me/zYyEtD\",\"url\":\"http://t.co/M9UUNvZi\"}],\"hashtags\":[],\"user_mentions\":[{\"id\":245888431,\"name\":\"TIME Moneyland\",\"indices\":[106,120],\"screen_name\":\"TIMEMoneyland\",\"id_str\":\"245888431\"}]},\"in_reply_to_status_id_str\":null,\"id\":159470076259602432,\"source\":\"<a href=\\\"http://www.hootsuite.com\\\" rel=\\\"nofollow\\\">HootSuite<\\/a>\",\"in_reply_to_user_id_str\":null,\"favorited\":false,\"in_reply_to_status_id\":null,\"retweet_count\":71,\"created_at\":\"Wed Jan 18 03:00:03 +0000 2012\",\"in_reply_to_user_id\":null,\"favorite_count\":14,\"id_str\":\"159470076259602432\",\"place\":null,\"user\":{\"location\":\"\",\"default_profile\":false,\"profile_background_tile\":true,\"statuses_count\":70754,\"lang\":\"en\",\"profile_link_color\":\"1B4F89\",\"profile_banner_url\":\"https://pbs.twimg.com/profile_banners/14293310/1355243462\",\"id\":14293310,\"following\":false,\"protected\":false,\"favourites_count\":59,\"profile_text_color\":\"000000\",\"description\":\"Breaking news and current events from around the globe. Hosted by TIME staff. Tweet questions to our customer service team @TIMEmag_Service.\",\"verified\":true,\"contributors_enabled\":false,\"profile_sidebar_border_color\":\"000000\",\"name\":\"TIME.com\",\"profile_background_color\":\"CC0000\",\"created_at\":\"Thu Apr 03 13:54:30 +0000 2008\",\"default_profile_image\":false,\"followers_count\":5146268,\"profile_image_url_https\":\"https://pbs.twimg.com/profile_images/1700796190/Picture_24_normal.png\",\"geo_enabled\":false,\"profile_background_image_url\":\"http://a0.twimg.com/profile_background_images/735228291/107f1a300a90ee713937234bb3d139c0.jpeg\",\"profile_background_image_url_https\":\"https://si0.twimg.com/profile_background_images/735228291/107f1a300a90ee713937234bb3d139c0.jpeg\",\"follow_request_sent\":false,\"entities\":{\"description\":{\"urls\":[]},\"url\":{\"urls\":[{\"expanded_url\":\"http://www.time.com\",\"indices\":[0,22],\"display_url\":\"time.com\",\"url\":\"http://t.co/4aYbUuAeSh\"}]}},\"url\":\"http://t.co/4aYbUuAeSh\",\"utc_offset\":-18000,\"time_zone\":\"Eastern Time (US & Canada)\",\"notifications\":false,\"profile_use_background_image\":true,\"friends_count\":742,\"profile_sidebar_fill_color\":\"D9D9D9\",\"screen_name\":\"TIME\",\"id_str\":\"14293310\",\"profile_image_url\":\"http://pbs.twimg.com/profile_images/1700796190/Picture_24_normal.png\",\"listed_count\":76944,\"is_translator\":false},\"coordinates\":null},\"contributors\":null,\"text\":\"RT @TIME: The Costa Concordia cruise ship accident could be a disaster for the industry | http://t.co/M9UUNvZi (via @TIMEMoneyland)\",\"geo\":null,\"retweeted\":false,\"in_reply_to_screen_name\":null,\"possibly_sensitive\":false,\"truncated\":false,\"lang\":\"en\",\"entities\":{\"symbols\":[],\"urls\":[{\"expanded_url\":\"http://ti.me/zYyEtD\",\"indices\":[90,110],\"display_url\":\"ti.me/zYyEtD\",\"url\":\"http://t.co/M9UUNvZi\"}],\"hashtags\":[],\"user_mentions\":[{\"id\":14293310,\"name\":\"TIME.com\",\"indices\":[3,8],\"screen_name\":\"TIME\",\"id_str\":\"14293310\"},{\"id\":245888431,\"name\":\"TIME Moneyland\",\"indices\":[116,130],\"screen_name\":\"TIMEMoneyland\",\"id_str\":\"245888431\"}]},\"in_reply_to_status_id_str\":null,\"id\":159475541894897679,\"source\":\"<a href=\\\"http://twitter.com/download/iphone\\\" rel=\\\"nofollow\\\">Twitter for iPhone<\\/a>\",\"in_reply_to_user_id_str\":null,\"favorited\":false,\"in_reply_to_status_id\":null,\"retweet_count\":71,\"created_at\":\"Wed Jan 18 03:21:46 +0000 2012\",\"in_reply_to_user_id\":null,\"favorite_count\":0,\"id_str\":\"159475541894897679\",\"place\":null,\"user\":{\"location\":\"\",\"default_profile\":false,\"profile_background_tile\":true,\"statuses_count\":5053,\"lang\":\"en\",\"profile_link_color\":\"738D84\",\"id\":27552112,\"following\":false,\"protected\":false,\"favourites_count\":52,\"profile_text_color\":\"97CEC9\",\"description\":\"\",\"verified\":false,\"contributors_enabled\":false,\"profile_sidebar_border_color\":\"A9AC00\",\"name\":\"rafael medina-flores\",\"profile_background_color\":\"C5EFE3\",\"created_at\":\"Mon Mar 30 01:21:55 +0000 2009\",\"default_profile_image\":false,\"followers_count\":963,\"profile_image_url_https\":\"https://pbs.twimg.com/profile_images/2519547938/image_normal.jpg\",\"geo_enabled\":true,\"profile_background_image_url\":\"http://a0.twimg.com/profile_background_images/167479660/trireme.jpg\",\"profile_background_image_url_https\":\"https://si0.twimg.com/profile_background_images/167479660/trireme.jpg\",\"follow_request_sent\":false,\"entities\":{\"description\":{\"urls\":[]}},\"url\":null,\"utc_offset\":-25200,\"time_zone\":\"Mountain Time (US & Canada)\",\"notifications\":false,\"profile_use_background_image\":true,\"friends_count\":1800,\"profile_sidebar_fill_color\":\"5C4F3C\",\"screen_name\":\"rmedinaflores\",\"id_str\":\"27552112\",\"profile_image_url\":\"http://pbs.twimg.com/profile_images/2519547938/image_normal.jpg\",\"listed_count\":50,\"is_translator\":false},\"coordinates\":null}" };

    String doc = (String) StringUtils.split(input[0], '\t').get(3);
    ObjectMapper mapper = StreamsJacksonMapper
            .getInstance(Lists.newArrayList(new TwitterDateTimeFormat().getFormat()));
    String outdoc = mapper.writeValueAsString(new TwitterJsonRetweetActivityConverter()
            .toActivityList(mapper.readValue(doc, Retweet.class)).get(0));

    String[] output = new String[1];
    output[0] = "(159475541894897679,twitter,statuses/user_timeline,1384499359006," + outdoc + ")";

    PigTest test;
    test = new PigTest("src/test/resources/pigconvertertest.pig");
    test.assertOutput("in", input, "out", output);

}

From source file:com.groupon.odo.controllers.GroupController.java

/**
 * Redirect to a edit group page/* ww  w. ja v  a2s.  c o  m*/
 *
 * @param model
 * @param groupId
 * @return
 * @throws Exception
 */
@RequestMapping(value = "group/{groupId}", method = RequestMethod.GET)
public String editGroup(Model model, @PathVariable int groupId) throws Exception {
    model.addAttribute("groupName", pathOverrideService.getGroupNameFromId(groupId));
    model.addAttribute("groupId", groupId);
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(pluginManager.getMethodsNotInGroup(groupId));
    model.addAttribute("methodsNotInGroup", json);

    return "editGroup";
}

From source file:com.hillert.botanic.ErrorMesssageTests.java

@Test
public void testErrorMessageSerialization() throws JsonProcessingException {

    ObjectMapper objectMapper = new ObjectMapper();

    ErrorMessage errorMessage = new ErrorMessage(new Date(), 404, "NotFoundException", "We did not find it.");
    String json = objectMapper.writeValueAsString(errorMessage);
    System.out.print(json);//from   w  w  w  .  j a v a 2  s.c om
}

From source file:org.example.spring.ApplicationTestDocumentation.java

@Test
public void getGreeting() throws Exception {

    /*RestDocumentationResultHandler document = documentPrettyPrintReqResp("getGreeting");
    document.snippets(/*from   w  w w .  ja  va 2  s . co  m*/
        pathParameters(greetingPathParams())
    );*/

    HelloRequest req = new HelloRequest();
    req.setName("Will");

    ObjectMapper objectMapper = new ObjectMapper();

    mockMvc.perform(post("/api/greeting").content(objectMapper.writeValueAsString(req))
            .contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(containsString("hello Will")))
            .andDo(document("hello"));
}

From source file:org.example.spring.ApplicationTestDocumentation.java

@Test
public void getGoodbye() throws Exception {

    //RestDocumentationResultHandler document = documentPrettyPrintReqResp("getGoodbye");
    /*document.snippets(
        pathParameters(greetingPathParams())
    );*///  www  .j  a  v  a  2s .  co m

    GoodbyeRequest req = new GoodbyeRequest();
    req.setFullname("Will Grigg");
    req.setName("Will");

    ObjectMapper objectMapper = new ObjectMapper();

    mockMvc.perform(post("/api/greeting").content(objectMapper.writeValueAsString(req))
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(content().string(containsString("goodbye Will Grigg"))).andDo(document("goodbye"));
}