Example usage for com.fasterxml.jackson.databind ObjectMapper writeValue

List of usage examples for com.fasterxml.jackson.databind ObjectMapper writeValue

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper writeValue.

Prototype

public void writeValue(Writer w, Object value)
        throws IOException, JsonGenerationException, JsonMappingException 

Source Link

Document

Method that can be used to serialize any Java value as JSON output, using Writer provided.

Usage

From source file:carmen.demo.LocationResolverDemo.java

public static void main(String[] args)
        throws ParseException, FileNotFoundException, IOException, ClassNotFoundException {
    // Parse the command line.
    String[] manditory_args = { "input_file" };
    createCommandLineOptions();//w  w  w  . java  2  s  .  c om
    CommandLineUtilities.initCommandLineParameters(args, LocationResolverDemo.options, manditory_args);

    // Get options
    String inputFile = CommandLineUtilities.getOptionValue("input_file");
    String outputFile = null;
    if (CommandLineUtilities.hasArg("output_file")) {
        outputFile = CommandLineUtilities.getOptionValue("output_file");
    }

    logger.info("Creating LocationResolver.");
    LocationResolver resolver = LocationResolver.getLocationResolver();

    Scanner scanner = Utils.createScanner(inputFile);

    Writer writer = null;
    if (outputFile != null) {
        writer = Utils.createWriter(outputFile);
        logger.info("Saving geolocated tweets to: " + outputFile);
    }
    ObjectMapper mapper = new ObjectMapper();
    int numResolved = 0;
    int total = 0;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        @SuppressWarnings("unchecked")
        HashMap<String, Object> tweet = (HashMap<String, Object>) mapper.readValue(line, Map.class);

        total++;
        Location location = resolver.resolveLocationFromTweet(tweet);

        if (location != null) {
            logger.debug("Found location: " + location.toString());
            numResolved++;
        }
        if (writer != null) {
            if (location != null) {
                tweet.put("location", Location.createJsonFromLocation(location));
            }
            mapper.writeValue(writer, tweet);
            writer.write("\n");
        }

    }
    scanner.close();
    if (writer != null)
        writer.close();

    logger.info("Resolved locations for " + numResolved + " of " + total + " tweets.");
}

From source file:cz.hobrasoft.pdfmu.jackson.SchemaGenerator.java

public static void main(String[] args) throws JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT); // nice formatting

    SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();

    Map<String, Type> types = new HashMap<>();
    types.put("RpcResponse", RpcResponse.class);
    types.put("result/inspect", Inspect.class);
    types.put("result/version set", VersionSet.class);
    types.put("result/signature add", SignatureAdd.class);
    types.put("result/empty", EmptyResult.class);

    for (Map.Entry<String, Type> e : types.entrySet()) {
        String name = e.getKey();
        String filename = String.format("schema/%s.json", name);
        Type type = e.getValue();
        mapper.acceptJsonFormatVisitor(mapper.constructType(type), visitor);
        JsonSchema jsonSchema = visitor.finalSchema();
        mapper.writeValue(new File(filename), jsonSchema);
    }//from  w  w w .  ja  va2  s.  c o  m
}

From source file:AdminExample.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    String accessToken = "";//Insert your access token here. Note this must be from an account that is an Admin of an account.
    String user1Email = ""; //You need access to these two email account.
    String user2Email = ""; //Note Gmail and Hotmail allow email aliasing. 
    //joe@gmail.com will get email sent to joe+user1@gmail.com 

    try {/*w w w . j  a v  a  2s. com*/
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Adding user " + user1Email);

        //Add the users:
        User user = new User();
        user.setEmail(user1Email);
        user.setAdmin(false);
        user.setLicensedSheetCreator(true);

        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), user);
        Result<User> newUser1Result = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<User>>() {
                });
        System.out.println(
                "User " + newUser1Result.result.email + " added with userId " + newUser1Result.result.getId());

        user = new User();
        user.setEmail(user2Email);
        user.setAdmin(true);
        user.setLicensedSheetCreator(true);

        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), user);
        Result<User> newUser2Result = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<User>>() {
                });
        System.out.println(
                "User " + newUser2Result.result.email + " added with userId " + newUser2Result.result.getId());
        System.out.println("Please visit the email inbox for the users " + user1Email + " and  " + user2Email
                + " and confirm membership to the account.");
        System.out.print("Press Enter to continue");
        in.readLine();

        //List all the users of the org
        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        List<User> users = mapper.readValue(connection.getInputStream(), new TypeReference<List<User>>() {
        });

        System.out.println("The following are members of your account: ");

        for (User orgUser : users) {
            System.out.println("\t" + orgUser.getEmail());
        }

        //Create a sheet as the admin
        Sheet newSheet = new Sheet();
        newSheet.setName("Admin's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //Create a sheet as user1
        newSheet = new Sheet();
        newSheet.setName("User 1's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        //Here is where the magic happens - Any action performed in this call will be on behalf of the
        //user provided. Note that this person must be a confirmed member of your org. 
        //Also note that the email address is url-encoded.
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user1Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //Create a sheet as user2
        newSheet = new Sheet();
        newSheet.setName("User 2's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //List all the sheets in the org:
        System.out.println("The following sheets are owned by members of your account: ");
        connection = (HttpURLConnection) new URL(USERS_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        List<Sheet> allSheets = mapper.readValue(connection.getInputStream(), new TypeReference<List<Sheet>>() {
        });

        for (Sheet orgSheet : allSheets) {
            System.out.println("\t" + orgSheet.getName() + " - " + orgSheet.getOwner());
        }

        //Now delete user1 and transfer their sheets to user2
        connection = (HttpURLConnection) new URL(USER_URL.replace(ID, newUser1Result.getResult().getId() + "")
                + "?transferTo=" + newUser2Result.getResult().getId()).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("DELETE");
        Result<Object> resultObject = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Object>>() {
                });

        System.out.println("Sheets transferred : " + resultObject.getSheetsTransferred());

    } catch (IOException e) {

        InputStream is = connection == null ? null : ((HttpURLConnection) connection).getErrorStream();
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            try {
                response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                Result<?> result = mapper.readValue(response.toString(), Result.class);
                System.err.println(result.message);

            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        e.printStackTrace();

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:SheetStructure.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    String accessToken = "";//Insert your access token here.

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

        System.out.println("Starting HelloSmartsheet2: Betty's Bake Sale...");
        //First Create a new sheet.
        String sheetName = "Betty's Bake Sale";
        //We will be using POJOs to represent the REST request objects. We will convert these to and from JSON using Jackson JSON.
        //Their structure directly relates to the JSON that gets passed through the API.
        //Note that these POJOs are included as static inner classes to keep this to one file. Normally they would be broken out.
        Sheet newSheet = new Sheet();
        newSheet.setName(sheetName);
        newSheet.setColumns(Arrays.asList(new Column("Baked Goods", "TEXT_NUMBER", null, true, null),
                new Column("Baker", "CONTACT_LIST", null, null, null),
                new Column("Price Per Item", "TEXT_NUMBER", null, null, null),
                new Column("Gluten Free?", "CHECKBOX", "FLAG", null, null), new Column("Status", "PICKLIST",
                        null, null, Arrays.asList("Started", "Finished", "Delivered"))));
        connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        Result<Sheet> newSheetResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Sheet>>() {
                });
        newSheet = newSheetResult.getResult();
        System.out.println("Sheet " + newSheet.getName() + " created, id: " + newSheet.getId());

        //Now add a column:
        String columnName = "Delivery Date";
        System.out.println("Adding column " + columnName + " to " + sheetName);
        Column newColumn = new Column(columnName, "DATE", 5);

        connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newColumn);
        Result<Column> newColumnResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Column>>() {
                });

        System.out.println(
                "Column " + newColumnResult.getResult().getTitle() + " added to " + newSheet.getName());

        //Next, we will get the list of Columns from the API. We could figure this out based on what the server has returned in the result, but we'll just ask the API for it.
        System.out.println("Fetching " + newSheet.getName() + " sheet columns...");
        connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        List<Column> allColumns = mapper.readValue(connection.getInputStream(),
                new TypeReference<List<Column>>() {
                });
        System.out.println("Fetched.");

        //Now we will be adding rows
        System.out.println("Inserting rows into " + newSheet.getName());
        List<Row> rows = new ArrayList<Row>();
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Brownies"),
                new Cell(allColumns.get(1).id, "julieann@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Finished"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Snickerdoodles"),
                new Cell(allColumns.get(1).id, "stevenelson@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"),
                new Cell(allColumns.get(5).id, "2013-09-04"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Rice Krispy Treats"),
                new Cell(allColumns.get(1).id, "rickthames@example.com"),
                new Cell(allColumns.get(2).id, "$.50"), new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Started"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Muffins"),
                new Cell(allColumns.get(1).id, "sandrassmart@example.com"),
                new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.FALSE),
                new Cell(allColumns.get(4).id, "Finished"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Chocolate Chip Cookies"),
                new Cell(allColumns.get(1).id, "janedaniels@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"),
                new Cell(allColumns.get(5).id, "2013-09-05"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Ginger Snaps"),
                new Cell(allColumns.get(1).id, "nedbarnes@example.com"), new Cell(allColumns.get(2).id, "$.50"),
                new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Unknown", false)))); //Note that this one is strict=false. This is because "Unknown" was not one of the original options when the column was created.

        RowWrapper rowWrapper = new RowWrapper();
        rowWrapper.setToBottom(true);
        rowWrapper.setRows(rows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> newRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + newRowsResult.getResult().size() + " rows to " + newSheet.getName());

        //Move a row to the top.
        System.out.println("Moving row 6 to the top.");
        RowWrapper moveToTop = new RowWrapper();
        moveToTop.setToTop(true);

        connection = (HttpURLConnection) new URL(
                ROW_URL.replace(ID, "" + newRowsResult.getResult().get(5).getId())).openConnection();
        connection.setRequestMethod("PUT");
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), moveToTop);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() {
        });

        System.out.println("Row 6 moved to top.");

        //Insert empty rows for spacing
        rows = new ArrayList<Row>();
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, ""))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Delivered"))));
        rowWrapper = new RowWrapper();
        rowWrapper.setToBottom(true);
        rowWrapper.setRows(rows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> spacerRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + spacerRowsResult.getResult().size() + " rows to " + newSheet.getName());

        //Move Delivered rows to be children of the last spacer row.
        System.out.println("Moving delivered rows to Delivered section...");
        Long[] deliveredRowIds = new Long[] { newRowsResult.result.get(1).getId(),
                newRowsResult.result.get(4).getId() };
        RowWrapper parentRowLocation = new RowWrapper();
        parentRowLocation.setParentId(spacerRowsResult.getResult().get(1).getId());

        for (Long deliveredId : deliveredRowIds) {
            System.out.println("Moving " + deliveredId + " to Delivered.");
            connection = (HttpURLConnection) new URL(ROW_URL.replace(ID, "" + deliveredId)).openConnection();
            connection.setRequestMethod("PUT");
            connection.addRequestProperty("Authorization", "Bearer " + accessToken);
            connection.addRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            mapper.writeValue(connection.getOutputStream(), parentRowLocation);
            mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() {
            });
            System.out.println("Row id " + deliveredId + " moved.");
        }

        System.out.println("Appending additional rows to items in progress...");

        List<Row> siblingRows = new ArrayList<Row>();
        siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Scones"),
                new Cell(allColumns.get(1).id, "tomlively@example.com"),
                new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Finished"))));
        siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Lemon Bars"),
                new Cell(allColumns.get(1).id, "rickthames@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Started"))));
        rowWrapper = new RowWrapper();
        rowWrapper.setSiblingId(newRowsResult.getResult().get(3).getId());
        rowWrapper.setRows(siblingRows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> siblingRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + siblingRowsResult.getResult().size() + " rows to " + newSheet.getName());

        System.out.println("Moving Status column to index 1...");
        Column statusColumn = allColumns.get(4);
        Column moveColumn = new Column();
        moveColumn.setIndex(1);
        moveColumn.setTitle(statusColumn.title);
        moveColumn.setSheetId(newSheet.getId());
        moveColumn.setType(statusColumn.getType());
        connection = (HttpURLConnection) new URL(COLUMN_URL.replace(ID, "" + statusColumn.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");

        mapper.writeValue(connection.getOutputStream(), moveColumn);
        Result<Column> movedColumnResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Column>>() {
                });
        System.out.println("Moved column " + movedColumnResult.getResult().getId());
        System.out.println("Completed Hellosmartsheet2: Betty's Bake Sale.");
    } catch (IOException e) {
        InputStream is = ((HttpURLConnection) connection).getErrorStream();
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            try {
                response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                Result<?> result = mapper.readValue(response.toString(), Result.class);
                System.err.println(result.message);

            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        e.printStackTrace();

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:de.phoenix.submissionpipeline.Core.java

private static void writeResult(ObjectMapper mapper, PhoenixSubmissionResult result) {
    try {//w  w  w . j  a  v a  2s .co m
        mapper.writeValue(System.out, result);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:ed.cracken.code.SimpleTestExp1.java

public static void writeAsJson(List<Map<?, ?>> data) throws IOException {
    StringWriter sw = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(sw, data);
    System.out.println(sw.toString());
}

From source file:org.pathirage.freshet.utils.ExpressionSerde.java

public static String serialize(Expression expression) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();

    StringWriter sw = new StringWriter();
    objectMapper.writeValue(sw, expression);

    return sw.toString();
}

From source file:org.cloudfoundry.dependency.OutputUtils.java

public static <T> Consumer<T> write(ObjectMapper objectMapper) {
    return value -> {
        try {//  ww  w  .j  a  v a2s. co  m
            objectMapper.writeValue(System.out, value);
        } catch (IOException e) {
            throw Exceptions.propagate(e);
        }
    };
}

From source file:org.apache.marmotta.platform.core.util.WebServiceUtil.java

/**
 * Create a JSON representation of an exception, to be returned to the client. The JSON object will be formatted
 * as follows:/*from ww  w.ja  v a2 s. co  m*/
 * <code>
 * {
 *     type: 'JAVA CLASS NAME',
 *     message: 'EXCEPTION MESSAGE'
 * }
 * </code>
 */
public static void jsonErrorResponse(Exception ex, OutputStream out) throws IOException {
    Map<String, Object> result = new HashMap<String, Object>();
    result.put("type", ex.getClass().getSimpleName());
    result.put("message", ex.getMessage());

    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(out, result);

}

From source file:org.kordamp.javatrove.example01.TestHelper.java

public static String repositoriesAsJSON(Collection<Repository> repositories, ObjectMapper objectMapper) {
    StringWriter writer = new StringWriter();
    try {//from w  ww  .ja va  2s .co  m
        objectMapper.writeValue(writer, repositories);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    return writer.toString();
}