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

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


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


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

Source Link


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


From source file:formats.db.fileformats.json.RunnerJSON.java

public static void main(String args[]) throws Exception {
    //        Customers c = new Customers(3, "Anna", "Dovlat", 0, "?392819");
    //        JSONObject json = new JSONObject();
    //        json.put("id_cs", c.getId_cs());
    //        json.put("f_name", c.getF_name());
    //        json.put("l_name", c.getL_name());
    //        json.put("discount", c.getDiscount());
    //        json.put("license", c.getLicense());
    //        System.out.println(json.toJSONString());
    //        String jString = json.toJSONString();
    ///*from  w w w  .j  a  v a  2  s .c o m*/
    //        ObjectMapper mapper = new ObjectMapper();
    //        Customers wasRead = mapper.readValue(jString, Customers.class);
    //        System.out.println(wasRead);

    Customers customers = new Customers(4, "Olga", "Petrova", 1, "?378492");
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(new File("D:\\customers.json"), customers);


From source file:tests.JSONOutput.java

public static void main(String[] main) throws IOException {

    ObjectMapper mapper = new ObjectMapper();
    File file = new File("./examples/");
    if (!file.exists()) {
        file.mkdir();//from   w  w  w .  j  a v  a 2s  .co m

        Keyspace k = new Keyspace("DDD");
        mapper.writeValue(new File("./examples/keyspace.json"), k);

            Table t = new Table(k, "tableName", "pk", "pkt");
            t.addColumn(new Column("columnName", "columnType"));

            mapper.writeValue(new File("./examples/table.json"), t);


            Table t = new Table();
            TableQuery query = new TableQuery();
            query.setCondition("WHERE name='bob' AND score >= 40");
            mapper.writeValue(new File("./examples/query.json"), query);



From source file:com.nextdoor.bender.CreateSchema.java

public static void main(String[] args) throws ParseException, InterruptedException, IOException {

    /*/*from w w  w . jav  a2 s  .c  om*/
     * Parse cli arguments
    Options options = new Options();
            .desc("Filename to output schema to. Default: schema.json").build());
            .desc("Create a schema that is able to be read by docson").build());
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    String filename = cmd.getOptionValue("out-file", "schema.json");

     * Write schema
    BenderSchema schema = new BenderSchema();
    ObjectMapper mapper = new ObjectMapper();

    JsonNode node = schema.getSchema();

    if (cmd.hasOption("docson")) {

    mapper.writeValue(new File(filename), node);

From source file:org.brnvrn.Main.java

public static void main(String[] args) {

    Document doc = null; // the HTML tool page
    Document docObsolete = null;/*from   w w w.j  av a 2s .  c o m*/
    try {
        //Document doc = Jsoup.connect("http://taskwarrior.org/tools/").get();
        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        InputStream input = classloader.getResourceAsStream("Taskwarrior-Tools.html");
        doc = Jsoup.parse(input, "UTF-8", "http://taskwarrior.org/");
        input = classloader.getResourceAsStream("Taskwarrior-Tools-Obsolete.html");
        docObsolete = Jsoup.parse(input, "UTF-8", "http://taskwarrior.org/");
    } catch (IOException e) {

    List<Tool> tools = new ArrayList<Tool>(100);
    ObjectMapper objectMapper = parseDocument(tools, doc, false);
    objectMapper = parseDocument(tools, docObsolete, true);

    try {
        objectMapper.writeValue(new FileOutputStream("data-tools.json"), tools);
    } catch (IOException e) {

From source file:com.fizzed.stork.test.HelloMain.java

static public void main(String[] args) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);

    HelloOutput output = new HelloOutput();
    output.setConfirm("Hello World!");

    mapper.writeValue(System.out, output);

From source file:org.n52.iceland.statistics.api.utils.KibanaExporter.java

public static void main(String args[]) throws Exception {
    if (args.length != 2) {
        System.out.printf("Usage: java KibanaExporter.jar %s %s\n", "localhost:9300", "my-cluster-name");
        System.exit(0);//from  w ww . j av  a2  s  .  c om
    if (!args[0].contains(":")) {
        throw new IllegalArgumentException(
                String.format("%s not a valid format. Expected <hostname>:<port>.", args[0]));

    // set ES address
    String split[] = args[0].split(":");
    InetSocketTransportAddress address = new InetSocketTransportAddress(InetAddress.getByName(split[0]),
            Integer.parseInt(split[1], 10));

    // set cluster name
    Builder tcSettings = Settings.settingsBuilder();
    tcSettings.put("cluster.name", args[1]);
    System.out.println("Connection to " + args[1]);

    client = TransportClient.builder().settings(tcSettings).build();

    // search index pattern for needle

    KibanaConfigHolderDto holder = new KibanaConfigHolderDto();
    System.out.println("Reading .kibana index");

    SearchResponse resp = client.prepareSearch(".kibana").setSize(1000).get();
    System.out.println("Reading finished");

    ObjectMapper mapper = new ObjectMapper();
    // we love pretty things
    File f = new File("kibana_config.json");

    try (FileOutputStream out = new FileOutputStream(f, false)) {
        mapper.writeValue(out, holder);

    System.out.println("File outputted to: " + f.getAbsolutePath());



From source file:jeplus.data.RVX.java

 * Tester/*from w  w w  .  j  ava 2s  .  c o m*/
 * @param args 
 * @throws java.io.IOException 
public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
    RVX rvx = mapper.readValue(new File("my.rvx"), RVX.class);
    mapper.writeValue(new File("user-modified.json"), rvx);

From source file:com.vethrfolnir.TestJsonAfterUnmarshal.java

public static void main(String[] args) throws Exception {
    ArrayList<TestThing> tsts = new ArrayList<>();

    for (int i = 0; i < 21; i++) {

        final int nr = i;
        tsts.add(new TestThing() {
            {/*from  w w w.  j a v  a  2  s  . c o  m*/
                id = 1028 * nr + 256;
                name = "Name-" + nr;

    ObjectMapper mp = new ObjectMapper();

    mp.configure(SerializationFeature.INDENT_OUTPUT, true);

    ByteArrayOutputStream br = new ByteArrayOutputStream();
    mp.writeValue(System.err, tsts);
    mp.writeValue(br, tsts);

    ByteArrayInputStream in = new ByteArrayInputStream(br.toByteArray());
    tsts = mp.readValue(in, new TypeReference<ArrayList<TestThing>>() {

    System.out.println("Got: " + tsts);

From source file:fr.cvlaminck.merging.samples.contacts.Application.java

public static void main(String[] args) throws IOException {
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);

    /**/*  w w w  .jav a  2  s.  c o  m*/
     * The first entry only contains mailing address.
    final Contact entry1 = new Contact("John", "Doe", "777. Rainbow road", "777", "City");
    System.out.println("/*             Entry : John Doe            */");
    objectMapper.writeValue(System.out, entry1);

     * The second entry considered as duplicate contains some phone numbers
     * for the contact
    final Contact entry2 = new Contact("John", "Doe", "+33777777777");
    System.out.println("/*           Duplicated : John Doe         */");
    objectMapper.writeValue(System.out, entry2);

     * Before doing any merge operation, we need to configure the merging library.
     * To configure the library, you need to instantiate a ValueMergers.
     * The ValuesMergers is a collection ValueMerger. This collection defines which
     * type of field can be merged by the library and which merging strategy can be
     * used for this type of field.
     * For the sample, we uses a PreConfiguredValueMergers that contains all ValueMerger
     * implemented in the core library. There is other implementation of ValueMergers that
     * you can use in your application.
    ValueMergers valueMergers = new DefaultValueMergers(); //TODO
    valueMergers.registerValueMerger(new UseRightIfLeftIsNullObjectValueMerger());
    valueMergers.registerValueMerger(new AddInRightCollectionValueMerger());

     * Then we instantiate the core element of the library.
     * The ObjectMerger is the object that will allow you to merge your objects.
    ObjectMerger objectMerger = new DefaultObjectMerger(valueMergers);

     * The last step before merging two objects together is to create an ObjectMergingStrategy.
     * This defines which merging strategy must be used to merge values contained in a field.
     * For this sample, we will use MutableObjectMergingStrategy implementation that allow you to define
     * the strategy at runtime.
    MutableObjectMergingStrategy objectMergingStrategy = new MutableObjectMergingStrategy(Contact.class);
    objectMergingStrategy.setDefaultStrategyForType(Object.class, MergingStrategies.useRightIfLeftIsNull);
    objectMergingStrategy.setDefaultStrategyForType(Collection.class, MergingStrategies.addInRightCollection);

     * Finally, we merge both objects and take a look at the result.
    final Contact result = objectMerger.merge(entry1, entry2, objectMergingStrategy);

    System.out.println("/*             Merged : John Doe           */");
    objectMapper.writeValue(System.out, result);

From source file:org.hcmut.emr.SessionBuilder.java

public static void main(String[] args) throws FileNotFoundException, IOException {
    try (BufferedReader br = new BufferedReader(
            new FileReader("/home/sinhlk/myspace/emr/src/main/resources/patern"))) {
        ObjectMapper jsonMapper = new ObjectMapper();
        String line = br.readLine();
        Map<String, String> result = new HashMap<String, String>();
        List<NameValuePair> list = new ArrayList<>();

        while (line != null) {
            if (line != null && line != "") {
                list.add(new BasicNameValuePair(line.trim().toLowerCase(), SessionBuilder.buildValue(line)));
                result.put(line.trim().toLowerCase(), SessionBuilder.buildValue(line));
                line = br.readLine();/*from   ww w .j  a va 2s .  c  om*/
        File file = new File("/home/sinhlk/myspace/emr/src/main/resources/session.js");
        jsonMapper.writeValue(file, list);