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.github.dockerjava.test.serdes.JSONTestHelper.java

/**
 * Performs roundtrip test for the specified class.
 * /*from w w w.j  a  va  2 s .com*/
 * @param <TClass>
 *            Item class
 * @param item
 *            Item to be checked
 * @param asclass
 *            Class to be used during conversions
 * @return Deserialized object after the roundtrip
 * @throws IOException
 *             JSON Conversion error
 * @throws AssertionError
 *             Validation error
 */
public static <TClass> TClass testRoundTrip(TClass item, Class<TClass> asclass)
        throws IOException, AssertionError {
    ObjectMapper mapper = new ObjectMapper();

    String serialized1 = mapper.writeValueAsString(item);
    JsonNode json1 = mapper.readTree(serialized1);
    TClass deserialized1 = mapper.readValue(serialized1, asclass);
    String serialized2 = mapper.writeValueAsString(deserialized1);
    JsonNode json2 = mapper.readTree(serialized2);
    TClass deserialized2 = mapper.readValue(serialized2, asclass);

    assertEquals(json2, json1, "JSONs must be equal after the second roundtrip");
    return deserialized2;
}

From source file:mercury.core.JSONUtils.java

public static String mapToJSON(Object object) {
    ObjectMapper mapper = new ObjectMapper();

    try {/*w  ww.  j  a v a 2  s.  c o  m*/

        return mapper.writeValueAsString(object);
    } catch (JsonProcessingException ex) {
        ImageJFX.getLogger();
        return "{}";
    }
}

From source file:org.axway.grapes.commons.utils.JsonUtils.java

/**
 * Serialize an object with Json//  www .  j ava  2s. c  o  m
 * @param obj Object
 * @return String
 * @throws IOException 
 */
public static String serialize(final Object obj) throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
    return mapper.writeValueAsString(obj);

}

From source file:org.apache.streams.gnip.powertrack.GnipActivityFixer.java

public static Activity fix(Activity activity) throws Exception {
    ObjectMapper mapper = new ObjectMapper();

    String des = mapper.writeValueAsString(activity);
    JSONObject json = new JSONObject(des);

    HashMap<ArrayList<String>, JSONObject> nullContents = new HashMap<ArrayList<String>, JSONObject>();
    ArrayList<String> drilldownKeys = new ArrayList<String>();

    findNullContents(json, drilldownKeys, nullContents);

    for (Map.Entry<ArrayList<String>, JSONObject> entry : nullContents.entrySet()) {
        JSONObject frag = entry.getValue();
        editJson(json, entry.getKey(), frag.get(""));
    }/*  ww  w. j  av  a2s  .c  om*/

    StringReader str = new StringReader(json.toString());
    Activity testAct = null;
    try {
        testAct = mapper.readValue(str, Activity.class);
    } catch (Exception e) {
        LOGGER.error("Exception creating activity.", e);
        LOGGER.error("JSON : {}" + json.toString());
    }

    return testAct;
}

From source file:au.org.ands.vocabs.toolkit.db.TaskUtils.java

/** Convert a Map to a String in JSON format. The Map can
 * be either an unsorted type (e.g., HashMap), or a sorted type
 * (i.e., a class that implements SortedMap, such as TreeMap).
 * For sorted types, key/value pairs are output in sorted order
 * based on keys.//www.  j  a va 2 s  .  c  o  m
 * If any values are also maps, the same respect for sortedness
 * applies to them.
 * (This behaviour relies on the Jackson library.)
 * @param map The Map to be converted. Generic types are used for
 *   both keys and values.
 * @return The Map converted to a String, in JSON format.
 */
public static String mapToJSONString(final Map<?, ?> map) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writeValueAsString(map);
    } catch (JsonProcessingException e) {
        logger.error("Exception in mapToJSONString", e);
        return "{\"exception\":\"Exception while " + "converting map to JSON\"}";
    }
}

From source file:au.org.ands.vocabs.toolkit.db.TaskUtils.java

/** Convert a Collection to a String in JSON format. The Collection can
 * be either an unsorted type (e.g., HashSet), or a sorted type
 * (i.e., a class that implements SortedSet, such as TreeSet).
 * For sorted types, output is in sorted order of values.
 * If any values are also Collections, the same respect for sortedness
 * applies to them.//from w ww .  j  a v  a  2 s  .co m
 * (This behaviour relies on the Jackson library.)
 * @param map The Collection to be converted.
 * @return The Collection converted to a String, in JSON format.
 */
public static String collectionToJSONString(final Collection<?> map) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writeValueAsString(map);
    } catch (JsonProcessingException e) {
        logger.error("Exception in collectionToJSONString", e);
        return "{\"exception\":\"Exception while " + "converting map to JSON\"}";
    }
}

From source file:com.auditbucket.engine.service.WhatServiceTest.java

public static String getJsonFromObject(Map<String, Object> what) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(what);
}

From source file:io.fouad.jtb.core.utils.JsonUtils.java

public static String toJson(Object javaObject) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
    return mapper.writeValueAsString(javaObject);
}

From source file:dk.dma.navnet.client.AbstractClientConnectionTest.java

protected static String persist(Object o) {
    ObjectMapper om = new ObjectMapper();
    om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    try {// w  ww.j a v  a 2  s. c om
        return om.writeValueAsString(o);
    } catch (JsonProcessingException e) {
        throw new IllegalArgumentException("Could not be persisted", e);
    }
}

From source file:fll.util.JsonUtilities.java

public static String generateJsonBracketInfo(final String division, final Map<Integer, Integer> ids,
        final Connection connection, final PerformanceScoreCategory perf, final BracketData bracketData,
        final boolean showOnlyVerifiedScores, final boolean showFinalsScores) {
    List<BracketLeafResultSet> datalist = new LinkedList<BracketLeafResultSet>();
    try {/*from   ww  w .  j a va  2 s . c o m*/
        final int currentTournament = Queries.getCurrentTournament(connection);
        for (Map.Entry<Integer, Integer> entry : ids.entrySet()) {
            final int row = entry.getKey();
            final int playoffRound = entry.getValue();
            final TeamBracketCell tbc = (TeamBracketCell) bracketData.getData(playoffRound, row);
            if (tbc == null) {
                return "{\"refresh\":\"true\"}";
            }
            final int numPlayoffRounds = Queries.getNumPlayoffRounds(connection);
            final int teamNumber = tbc.getTeam().getTeamNumber();
            final int runNumber = Playoff.getRunNumber(connection, division, teamNumber, playoffRound);
            final TeamScore teamScore = new DatabaseTeamScore("Performance", currentTournament, teamNumber,
                    runNumber, connection);
            final double computedTeamScore = perf.evaluate(teamScore);
            final boolean realScore = !Double.isNaN(computedTeamScore);
            final boolean noShow = Queries.isNoShow(connection, currentTournament,
                    tbc.getTeam().getTeamNumber(), runNumber);
            // Sane request checks
            if (noShow) {
                datalist.add(new BracketLeafResultSet(tbc, -2.0, row + "-" + playoffRound));
            } else if (!realScore || !showOnlyVerifiedScores
                    || Queries.isVerified(connection, currentTournament, teamNumber, runNumber)) {
                if ((playoffRound == numPlayoffRounds && !showFinalsScores) || !realScore) {
                    datalist.add(new BracketLeafResultSet(tbc, -1.0, row + "-" + playoffRound));
                } else {
                    datalist.add(new BracketLeafResultSet(tbc, computedTeamScore, row + "-" + playoffRound));
                }
            }
        }
    } catch (final SQLException e) {
        throw new RuntimeException(e);
    }
    if (datalist.size() == 0) {
        // Add some data, JSON is happy
        datalist.add(new BracketLeafResultSet());
    }
    try {
        final ObjectMapper jsonMapper = new ObjectMapper();
        return jsonMapper.writeValueAsString(datalist);
    } catch (final JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}