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

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

Introduction

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

Prototype

public ObjectMapper() 

Source Link

Document

Default constructor, which will construct the default JsonFactory as necessary, use SerializerProvider as its SerializerProvider , and BeanSerializerFactory as its SerializerFactory .

Usage

From source file:test.jackson.TestJacksonPoly.java

public static void main(String[] args) {

    ObjectMapper objectMapper = new ObjectMapper();

    Animal myDog = new Dog("ruffus", "english shepherd");

    Animal myCat = new Cat("goya", "mice");

    try {/*from  www  .jav  a  2s  .  co  m*/
        String dogJson = objectMapper.writeValueAsString(myDog);

        System.out.println(dogJson);

        Animal deserializedDog = objectMapper.readValue(dogJson, Animal.class);

        System.out.println("Deserialized dogJson Class: " + deserializedDog.getClass().getSimpleName());

        String catJson = objectMapper.writeValueAsString(myCat);

        Animal deseriliazedCat = objectMapper.readValue(catJson, Animal.class);

        System.out.println("Deserialized catJson Class: " + deseriliazedCat.getClass().getSimpleName());

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.titan.main.Invoker.java

public static void main(String... args) {
    try {//w  w w.java2  s  . c om
        NotificationsFactory factory = new NotificationsFactory();

        ObjectMapper mapper = new ObjectMapper();
        mapper.addMixInAnnotations(Notifications.class, NotificationsMixin.class);
        mapper.addMixInAnnotations(NotificationsInfo.class, NotificationsInfoMixin.class);

        Notifications notifications = factory.getNotifications();

        mapper.writerWithDefaultPrettyPrinter().writeValue(
                new File("D:/workspace/nbworkspace/jackson-sample/notifications.json"), notifications);

        System.out.println("Done!");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.sinosoft.dtphone.vehicle.findCar.main.Main.java

/**
 * @param args/*w  w  w.j  a va 2  s. co  m*/
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    objectMapper = new ObjectMapper();
    String body = null;
    Domain test = null;
    try {
        test = getTB();
        jsonGenerator = objectMapper.getFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
        jsonGenerator.writeObject(test);
        // System.out.println();
        // objectMapper.writeValue(System.out, test);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:edu.usd.btl.ontology.ToolTree.java

public static void main(String[] args) throws Exception {
    try {//from  w w  w.  j ava  2 s.  co m
        //File ontoInput = new File(".\\ontology_files\\EDAM_1.3.owl");
        ObjectMapper mapper = new ObjectMapper();
        OntologyFileRead ontFileRead = new OntologyFileRead();
        ArrayList<edu.usd.btl.ontology.BioPortalElement> nodeList = ontFileRead
                .readFile(".\\ontology_files\\EDAM_1.3.owl");
        //write nodelist to JSON string
        ObjectWriter treeWriter = mapper.writer().withDefaultPrettyPrinter();
        String edamJSON = mapper.writeValueAsString(nodeList);

        JsonNode rootNode = mapper.readValue(edamJSON, JsonNode.class);
        System.out.println("IsNull" + rootNode.toString());

        OntSearch ontSearch = new OntSearch();
        System.out.println(nodeList.get(0).getURI());
        String result = ontSearch.searchElementByURI("http://edamontology.org/topic_2817");
        System.out.println("RESULT = " + result);

        String topicSearchResult = ontSearch.findAllTopics();
        System.out.println("Topics Result = " + topicSearchResult);

        File ontFile = new File(".\\ontology_files\\EDAM_1.3.owl");
        String searchFromFileResult = ontSearch.searchNodeFromFile("http://edamontology.org/topic_2817",
                ".\\ontology_files\\EDAM_1.3.owl");
        System.out.println("File Response = " + searchFromFileResult.toString());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

    //Hashmap stuff
    //        OntologyFileRead ontFileRead = new OntologyFileRead();
    //        ArrayList<edu.usd.btl.ontology.BioPortalElement> nodeList = ontFileRead.readFile(".\\ontology_files\\EDAM_1.3.owl");
    //        
    //        HashMap hm = new HashMap();
    //        
    //        //find topics
    //        ArrayList<OntologyNode> ontoTopicList = new ArrayList();
    //        
    //        for(BioPortalElement node : nodeList){
    //            //System.out.println("****" + node.getURI());
    //            hm.put(node.getURI(), node.getName());
    //        }
    //        
    //        Set set = hm.entrySet();
    //        Iterator i = set.iterator();
    //        while(i.hasNext()){
    //            Map.Entry me = (Map.Entry)i.next();
    //            System.out.println(me.getKey() + ": " + me.getValue());
    //        }
    //        System.out.println("HashMap Size = " + hm.size());
}

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!");
    output.setEnvironment(System.getenv());
    output.setSystemProperties(System.getProperties());
    output.setArguments(Arrays.asList(args));

    mapper.writeValue(System.out, output);
}

From source file:org.dawnsci.commandserver.mx.example.TestMarshall.java

public static void main(String[] args) throws Exception {

    // We want to get the JSON string for this:
    SweepBean col = new SweepBean("fred", "d0000000001", 0, 100);
    ProjectBean bean = new ProjectBean();
    bean.addSweep(col);/*from w ww  .  j  a va 2 s  . c  om*/
    bean.setStatus(Status.SUBMITTED);
    bean.setPercentComplete(10);

    ObjectMapper mapper = new ObjectMapper();
    String jsonString = mapper.writeValueAsString(bean);

    System.out.println(jsonString);

    final ProjectBean beanBack = mapper.readValue(jsonString, ProjectBean.class);
    System.out.println("Read in equals written out = " + beanBack.equals(bean));
}

From source file:spatialluceneindexer.Main.java

/**
 * @param args the command line arguments
 *///w  w  w .j  a va 2  s  .co m
public static void main(String[] args) {

    System.out.println("Starting to create the index");

    //Open the file of JSON for reading
    FileOpener fOpener = new FileOpener("parks.json");

    //Create the object for writing
    LuceneWriter luceneWriter = new LuceneWriter("indexDir");

    //This is from Jackson which allows for binding the JSON to the Park.java class
    ObjectMapper objectMapper = new ObjectMapper();

    try {

        //first see if we can open a directory for writing
        if (luceneWriter.openIndex()) {
            //get a buffered reader handle to the file
            BufferedReader breader = new BufferedReader(fOpener.getFileForReading());
            String value = null;
            //loop through the file line by line and parse 
            while ((value = breader.readLine()) != null) {
                Park park = objectMapper.readValue(value, Park.class);

                //now submit each park to the lucene writer to add to the index
                luceneWriter.addPark(park);

            }

        } else {
            System.out.println("We had a problem opening the directory for writing");
        }

    } catch (Exception e) {
        System.out.println("Threw exception " + e.getClass() + " :: " + e.getMessage());
    } finally {
        luceneWriter.finish();
    }

    System.out.println("Finished created the index");
}

From source file:luceneindexer.Main.java

/**
 * @param args the command line arguments
 *//*from w  w  w.  j  a  va  2  s . c om*/
public static void main(String[] args) {
    // TODO code application logic here
    System.out.println("Hello world");
    //Open the file of JSON for reading
    FileOpener fOpener = new FileOpener("parks.json");

    //Create the object for writing
    LuceneWriter luceneWriter = new LuceneWriter("indexDir");

    //This is from Jackson which allows for binding the JSON to the Park.java class
    ObjectMapper objectMapper = new ObjectMapper();

    try {

        //first see if we can open a directory for writing
        if (luceneWriter.openIndex()) {
            //get a buffered reader handle to the file
            BufferedReader breader = new BufferedReader(fOpener.getFileForReading());
            String value = null;
            //loop through the file line by line and parse 
            while ((value = breader.readLine()) != null) {
                Park park = objectMapper.readValue(value, Park.class);

                //now submit each park to the lucene writer to add to the index
                luceneWriter.addPark(park);

            }

        } else {
            System.out.println("We had a problem opening the directory for writing");
        }

    } catch (Exception e) {
        System.out.println("Threw exception " + e.getClass() + " :: " + e.getMessage());
    } finally {
        //close out the index and release the lock on the file
        luceneWriter.finish();
    }

}

From source file:de.fionera.javamailer.main.Main.java

/**
 * The Main Class which will be started// w  ww  . j ava 2  s  .  c om
 *
 * @param args
 */
public static void main(String[] args) {
    ObjectMapper mapper = new ObjectMapper();
    File file = new File("settings.jm");

    try {
        loadSettings(file, mapper);
    } catch (Exception e) {
        e.printStackTrace();
    }

    controllerMain controllerMain = new controllerMain();
    controllerMain.createMainView();

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        saveSettings(file, mapper);
    }));
}

From source file:com.enitalk.controllers.youtube.CalendarTest.java

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

    InputStream is = new ClassPathResource("events.json").getInputStream();
    ObjectMapper jackson = new ObjectMapper();
    JsonNode tree = jackson.readTree(is);
    IOUtils.closeQuietly(is);//from   w w  w  .j  a v  a2  s  . c  o  m

    DateTimeFormatter fmtDateTime = ISODateTimeFormat.dateTimeNoMillis();
    DateTimeFormatter fmt = ISODateTimeFormat.date();

    TreeMultimap<DateTime, DateTime> set = CalendarTest.getPeriodSet(10, 18);

    Iterator<JsonNode> nodes = tree.elements();
    while (nodes.hasNext()) {
        JsonNode ev = nodes.next();
        boolean isFullDay = ev.path("start").has("date");

        DateTime stDate = isFullDay ? fmt.parseDateTime(ev.path("start").path("date").asText())
                : fmtDateTime.parseDateTime(ev.path("start").path("dateTime").asText());

        DateTime enDate = isFullDay ? fmt.parseDateTime(ev.path("end").path("date").asText())
                : fmtDateTime.parseDateTime(ev.path("end").path("dateTime").asText());

        System.out.println("St " + stDate + " en " + enDate);

        int days = Days.daysBetween(stDate, enDate).getDays();
        System.out.println("Days between " + days);
        if (isFullDay) {
            switch (days) {
            case 1:
                set.removeAll(stDate);
                break;
            default:
                while (days-- > 0) {
                    set.removeAll(stDate.plusDays(days));
                }
            }
        } else {
            DateTime copySt = stDate.minuteOfHour().setCopy(0).secondOfMinute().setCopy(0);
            DateTime copyEn = enDate.plusHours(1).minuteOfHour().setCopy(0).secondOfMinute().setCopy(0);

            //                System.out.println("Dates truncated " + copySt + " " + copyEn);
            //                System.out.println("Ll set " + set);

            //                System.out.println("Getting set for key " + stDate.millisOfDay().setCopy(0));
            SortedSet<DateTime> ss = set.get(stDate.millisOfDay().setCopy(0));
            SortedSet<DateTime> subset = ss.subSet(copySt, copyEn);
            subset.clear();
            set.remove(enDate.millisOfDay().setCopy(0), copyEn);
        }

    }

}