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:ru.deltasolutions.utils.file.transfer.SFTPFileTransferConfig.java

@Override
public String toString() {
    ObjectMapper mapper = new ObjectMapper();
    try {/*from ww w  .  j av  a  2  s. c om*/
        String str = mapper.writeValueAsString(this);
        return str;
    } catch (JsonProcessingException e) {
        return null;
    }
}

From source file:org.springframework.security.jackson2.UserDeserializerTests.java

@Test
public void serializeUserWithoutAuthority() throws JsonProcessingException, JSONException {
    ObjectMapper mapper = buildObjectMapper();
    User user = new User("admin", "1234", Collections.<GrantedAuthority>emptyList());
    String userJson = mapper.writeValueAsString(user);
    String expectedJson = "{\"@class\": \"org.springframework.security.core.userdetails.User\", \"username\": \"admin\", \"password\": \"1234\", \"accountNonExpired\": true, \"accountNonLocked\": true, \"credentialsNonExpired\": true, \"enabled\": true, \"authorities\": [\"java.util.Collections$UnmodifiableSet\", []]}";
    JSONAssert.assertEquals(expectedJson, userJson, true);
}

From source file:com.callidusrobotics.droptables.model.ReportGeneratorTest.java

@Test
public void toJsonSuccess() throws Exception {
    reportGenerator = ModelUtil.buildReport();
    reportGenerator.id = new ObjectId("54e8f1dbd9a93c9b467d5380");
    reportGenerator.script = GOOD_SCRIPT;
    reportGenerator.template = GOOD_TEMPLATE;
    reportGenerator.setCreated(new Date(1111111));
    reportGenerator.setModified(new Date(5555555));
    reportGenerator.setName("Script1");
    reportGenerator.setDescription("This is a script for testing serialization");

    String expectedJson = "{\"id\":{\"date\":1424552411000,\"time\":1424552411000,\"timestamp\":1424552411,\"timeSecond\":1424552411,\"inc\":1182618496,\"machine\":-643220325,\"new\":false},\"dateCreated\":1111111,\"dateModified\":5555555,\"name\":\"Script1\",\"description\":\"This is a script for testing serialization\",\"author\":\"John Doe\",\"language\":\"GROOVY\",\"template\":\"<html><% print [0, 1, 2] %></html>\",\"script\":\"var1 = [0, 1, 2]\\nprint var1\",\"defaultParameters\":{\"foo\":{\"type\":\"STRING\",\"tooltip\":\"Value for foo\",\"values\":[\"bar\"]}}}";

    // Unit under test
    ObjectMapper mapper = new ObjectMapper();
    String result = mapper.writeValueAsString(reportGenerator);

    // Verify results
    JSONAssert.assertJsonEquals(expectedJson, result);
}

From source file:com.insilico.titan.Framez.java

public void queryGraph(TitanGraph graph, FramedGraph framedGraph) {
    try {/*from  w  w w.  j a  va 2s  .  c  o m*/
        Iterable<Person> itv = framedGraph.getVertices("type", "person", Person.class);
        for (Person p : itv) {
            //System.out.println(p);
        }
        //Person person = (Person) framedGraph.getVertices("name","vijay",Person.class);
        // System.out.println(person);
        //System.out.println(person.getName());

        GremlinPipeline pipe = new GremlinPipeline();

        Iterator itr = graph.getVertices().iterator();
        while (itr.hasNext()) {
            Vertex v = (Vertex) itr.next();
            //System.out.println(v.getId());
            Set<String> set = v.getPropertyKeys();
            for (String s : set) {
                //System.out.println(v.getId()+"="+s);
            }
        }

        //System.out.println(graph.getVertex("002"));
        //pipe.start(framedGraph.getVertices("type", "person",Person.class));

        pipe.start(graph.getVertices());
        pipe.has("age", GREATER_THAN, 65);
        pipe.has("name", CONTAINS, "giri");
        //pipe.filter();
        //pipe2.start(framedGraph.getVertices("name", "vijay",Person.class));
        //pipe3.start(framedGraph.getVertices("name", "friend",Person.class));

        //pipe.addPipe(pipe1);
        //pipe.addPipe(pipe2);
        //pipe.addPipe(pipe3);

        //System.out.println(pipe.count());
        //Iterator<Person> i = pipe.iterator();uid
        ArrayList q = new ArrayList();
        while (pipe.hasNext()) {
            //Person y = (Person) pipe.next();
            Vertex x = (Vertex) pipe.next();
            System.out.println(x.getId());
            Person y = (Person) framedGraph.getVertex(x.getId(), Person.class);
            HashMap m = y.getProps();
            q.add(y);
            ObjectMapper mapper = new ObjectMapper();
            System.out.println(y.getUID() + "=" + mapper.writeValueAsString(y));
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.rhc.dynamic.pipeline.ObjectMother.java

/**
 * Helper method to generate json to be used in test 
 * @throws JsonProcessingException/*from   w w  w . j av  a 2 s .c o  m*/
 */
@Test
public void shouldGenerateSomeStuff() throws JsonProcessingException {
    String applicationName = "cool-application-name";
    Engagement engagement = buildSingleClusterMultiProjectEngagementNoBuildTool(applicationName);
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    String output = mapper.writeValueAsString(engagement);
    LOGGER.info("\n\n" + output + "\n\n");
}

From source file:com.yahoo.elide.datastores.hibernate3.usertypes.JsonType.java

/**
 * {@inheritDoc}/* w w  w .j av  a 2s  .c o m*/
 */
@Override
public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index)
        throws HibernateException, SQLException {

    if (value == null) {
        preparedStatement.setNull(index, Types.NULL);
    } else {
        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(value);
            preparedStatement.setString(index, json);
        } catch (JsonProcessingException e) {
            throw new HibernateException(
                    "Could not write an instance of the mapped class to a prepared statement.");
        }
    }
}

From source file:org.jasig.cas.support.oauth.web.OAuth20TokenRefreshTokenController.java

@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final String refreshTokenId = request.getParameter(OAuthConstants.REFRESH_TOKEN);
    LOGGER.debug("{} : {}", OAuthConstants.REFRESH_TOKEN, refreshTokenId);

    final String clientId = request.getParameter(OAuthConstants.CLIENT_ID);
    LOGGER.debug("{} : {}", OAuthConstants.CLIENT_ID, clientId);

    final String clientSecret = request.getParameter(OAuthConstants.CLIENT_SECRET);
    LOGGER.debug("{} : {}", OAuthConstants.CLIENT_SECRET, "*********");

    final String grantType = request.getParameter(OAuthConstants.GRANT_TYPE);
    LOGGER.debug("{} : {}", OAuthConstants.GRANT_TYPE, grantType);

    try {//from  ww  w.  jav a2 s  . c o m
        verifyRequest(refreshTokenId, clientId, clientSecret, grantType);
    } catch (final InvalidParameterException e) {
        return OAuthUtils.writeJsonError(response, OAuthConstants.INVALID_REQUEST, e.getMessage(),
                HttpStatus.SC_BAD_REQUEST);
    }

    final RefreshToken refreshToken;
    try {
        refreshToken = centralOAuthService.getToken(refreshTokenId, RefreshToken.class);
    } catch (final InvalidTokenException e) {
        LOGGER.error("Invalid {} : {}", OAuthConstants.REFRESH_TOKEN, refreshTokenId);
        return OAuthUtils.writeJsonError(response, OAuthConstants.INVALID_REQUEST,
                OAuthConstants.INVALID_REFRESH_TOKEN_DESCRIPTION, HttpStatus.SC_BAD_REQUEST);
    }

    final AccessToken accessToken = centralOAuthService.grantOfflineAccessToken(refreshToken);

    final Map<String, Object> map = new HashMap<>();
    map.put(OAuthConstants.ACCESS_TOKEN, accessToken.getId());
    map.put(OAuthConstants.EXPIRES_IN, (int) (timeout - TimeUnit.MILLISECONDS
            .toSeconds(System.currentTimeMillis() - accessToken.getTicket().getCreationTime())));
    map.put(OAuthConstants.TOKEN_TYPE, OAuthConstants.BEARER_TOKEN);

    final ObjectMapper mapper = new ObjectMapper();
    final String result = mapper.writeValueAsString(map);
    LOGGER.debug("result : {}", result);

    response.setContentType("application/json");
    return OAuthUtils.writeText(response, result, HttpStatus.SC_OK);
}

From source file:com.epam.marshaller.jackson.JacksonMarshallerTest.java

@Test
public void testMarshaller() throws IOException {
    ObjectMapper objectMapper = prepareObjectMapper();
    User user = prepareUser();//ww  w . j  av  a  2s.  c  o m

    String userJson = objectMapper.writeValueAsString(user);
    print(userJson);

    User unmarshalledUser = objectMapper.readValue(userJson, User.class);

    Assert.assertEquals(user, unmarshalledUser);
}

From source file:com.samlikescode.stackoverflow.questions.q30979488.MessageMixInTest.java

@Test
public void testMixInRoundTrip() throws IOException {
    ObjectMapper om = new ObjectMapper().addMixIn(Message.class, MessageMixin.class);

    Message message = new Message(new Member("Bob", 883l), new Member("Jilly", 3993l));

    String output = om.writeValueAsString(message);
    System.out.println(output);//from w ww.  j  a v a 2s  .  com
}

From source file:com.yahoo.elide.datastores.hibernate5.usertypes.JsonType.java

/**
 * {@inheritDoc}//  w w w.ja  v  a2s  .  co  m
 */
@Override
public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index,
        SessionImplementor session) throws HibernateException, SQLException {

    if (value == null) {
        preparedStatement.setNull(index, Types.NULL);
    } else {
        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(value);
            preparedStatement.setString(index, json);
        } catch (JsonProcessingException e) {
            throw new HibernateException(
                    "Could not write an instance of the mapped class to a prepared statement.");
        }
    }
}