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

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
    public <T> T readValue(byte[] src, JavaType valueType)
            throws IOException, JsonParseException, JsonMappingException 

Source Link

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 {//ww w  . j av  a  2 s .c  o  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:test.SemanticConverter.java

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

    SemanticConverter ri = new SemanticConverter();

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    RegisterContextRequest rcr = new RegisterContextRequest();
    try {/*w w  w. jav a2s.c om*/
        rcr = objectMapper.readValue(ri.NGSI_FILE, RegisterContextRequest.class);
    } catch (Exception e) {

    }
    //        RegisterContextRequest rcr = rm.unmarshallRequest(ri.NGSI_FILE);
    rcr.setTimestamp(Instant.now());
    ri.createJenaModel(rcr);

    //        //hMap.put("class", "OnDeviceResource"); 
    ////        hMap.put("class", new String[]{"ResourceService"});
    //        hMap.put("class", new String[]{"VirtualEntity"});
    ////        hMap.put("hasID", new String[]{"Resource_1"});
    //        hMap.put("hasID", new String[]{"VirtualEntity_1"});
    //        hMap.put("hasAttributeType", new String[]{"http://purl.oclc.org/NET/ssnx/qu/quantity#temperature"});     
    ////        hMap.put("isHostedOn", "PloggBoard_49_BA_01_light");
    ////        hMap.put("hasType", "Sensor");
    ////        hMap.put("hasName", "lightsensor49_BA_01");
    ////        hMap.put("isExposedThroughService", "http://www.surrey.ac.uk/ccsr/ontologies/ServiceModel.owl#49_BA_01_light_sensingService");
    ////        hMap.put("hasTag", "light sensor 49,1st,BA,office");
    //        hMap.put("hasLatitude", new String[]{"51.243455"});
    ////        hMap.put("hasGlobalLocation", "http://www.geonames.org/2647793/");
    ////        hMap.put("hasResourceID", "Resource_53_BA_power_sensor");
    ////        hMap.put("hasLocalLocation", "http://www.surrey.ac.uk/ccsr/ontologies/LocationModel.owl#U49");
    //        hMap.put("hasAltitude", new String[]{""});
    //        hMap.put("hasLongitude", new String[]{"-0.588088"});
    ////        hMap.put("hasTimeOffset", "20");
    //
    //        //ri.ONT_URL = "http://www.surrey.ac.uk/ccsr/ontologies/ServiceModel.owl#";
    //        //ri.ONT_URL = "http://www.surrey.ac.uk/ccsr/ontologies/VirtualEntityModel.owl#";
    //        //ri.ONT_FILE = "web/IoTA-Models/VirtualEntityModel.owl";
    //        ri.createJenaModel(hMap);
}

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();//from w ww .  j a v a  2  s  . c o  m
    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:com.basistech.rosette.dm.json.array.CompareJsons.java

public static void main(String[] args) throws Exception {
    File plenty = new File(args[0]);
    System.out.println(String.format("Original file length %d", plenty.length()));
    ObjectMapper inputMapper = AnnotatedDataModelModule.setupObjectMapper(new ObjectMapper());
    AnnotatedText[] texts = inputMapper.readValue(plenty, AnnotatedText[].class);
    System.out.println(String.format("%d documents", texts.length));
    runWithFormat(texts, new FactoryFactory() {
        @Override//from   w  ww.  j  a v a 2 s.c o  m
        public JsonFactory newFactory() {
            return new JsonFactory();
        }
    }, "Plain");
    runWithFormat(texts, new FactoryFactory() {
        @Override
        public JsonFactory newFactory() {
            return new SmileFactory();
        }
    }, "SMILE");

    runWithFormat(texts, new FactoryFactory() {
        @Override
        public JsonFactory newFactory() {
            return new CBORFactory();
        }
    }, "CBOR");
}

From source file:net.e2.bw.idreg.db2ldif.Db2Ldif.java

/**
 * Main method/*  w w  w  .  ja v a  2 s  . co  m*/
 * @param args runtime arguments
 */
public static void main(String[] args) throws Exception {
    Db2Ldif db2ldif = new Db2Ldif();

    // Preload company data from json file
    ObjectMapper mapper = new ObjectMapper();
    List<Company> companies = mapper.readValue(Db2Ldif.class.getResource("/companies.json"),
            new TypeReference<List<Company>>() {
            });
    companies.forEach(c -> db2ldif.companyData.put(c.uid, c));

    new JCommander(db2ldif, args);
    db2ldif.execute();
}

From source file:test.SemanticConverter2.java

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

    SemanticConverter2 ri = new SemanticConverter2();

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    RegisterContextRequest rcr = new RegisterContextRequest();
    try {//ww  w  .  ja  v  a  2s. com
        rcr = objectMapper.readValue(ri.NGSI_FILE, RegisterContextRequest.class);
    } catch (Exception e) {

    }
    rcr.setTimestamp(Instant.now());
    ri.createJenaModel(rcr);

    //        //hMap.put("class", "OnDeviceResource"); 
    ////        hMap.put("class", new String[]{"ResourceService"});
    //        hMap.put("class", new String[]{"VirtualEntity"});
    ////        hMap.put("hasID", new String[]{"Resource_1"});
    //        hMap.put("hasID", new String[]{"VirtualEntity_1"});
    //        hMap.put("hasAttributeType", new String[]{"http://purl.oclc.org/NET/ssnx/qu/quantity#temperature"});     
    ////        hMap.put("isHostedOn", "PloggBoard_49_BA_01_light");
    ////        hMap.put("hasType", "Sensor");
    ////        hMap.put("hasName", "lightsensor49_BA_01");
    ////        hMap.put("isExposedThroughService", "http://www.surrey.ac.uk/ccsr/ontologies/ServiceModel.owl#49_BA_01_light_sensingService");
    ////        hMap.put("hasTag", "light sensor 49,1st,BA,office");
    //        hMap.put("hasLatitude", new String[]{"51.243455"});
    ////        hMap.put("hasGlobalLocation", "http://www.geonames.org/2647793/");
    ////        hMap.put("hasResourceID", "Resource_53_BA_power_sensor");
    ////        hMap.put("hasLocalLocation", "http://www.surrey.ac.uk/ccsr/ontologies/LocationModel.owl#U49");
    //        hMap.put("hasAltitude", new String[]{""});
    //        hMap.put("hasLongitude", new String[]{"-0.588088"});
    ////        hMap.put("hasTimeOffset", "20");
    //
    //        //ri.ONT_URL = "http://www.surrey.ac.uk/ccsr/ontologies/ServiceModel.owl#";
    //        //ri.ONT_URL = "http://www.surrey.ac.uk/ccsr/ontologies/VirtualEntityModel.owl#";
    //        //ri.ONT_FILE = "web/IoTA-Models/VirtualEntityModel.owl";
    //        ri.createJenaModel(hMap);
}

From source file:test.SemanticConverter3.java

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

    SemanticConverter3 ri = new SemanticConverter3();

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    RegisterContextRequest rcr = new RegisterContextRequest();
    try {/*from   w w w .  jav  a 2  s. co m*/
        rcr = objectMapper.readValue(ri.NGSI_FILE, RegisterContextRequest.class);
    } catch (Exception e) {

    }
    rcr.setTimestamp(Instant.now());
    ri.createJenaModel(rcr);

    //        //hMap.put("class", "OnDeviceResource"); 
    ////        hMap.put("class", new String[]{"ResourceService"});
    //        hMap.put("class", new String[]{"VirtualEntity"});
    ////        hMap.put("hasID", new String[]{"Resource_1"});
    //        hMap.put("hasID", new String[]{"VirtualEntity_1"});
    //        hMap.put("hasAttributeType", new String[]{"http://purl.oclc.org/NET/ssnx/qu/quantity#temperature"});     
    ////        hMap.put("isHostedOn", "PloggBoard_49_BA_01_light");
    ////        hMap.put("hasType", "Sensor");
    ////        hMap.put("hasName", "lightsensor49_BA_01");
    ////        hMap.put("isExposedThroughService", "http://www.surrey.ac.uk/ccsr/ontologies/ServiceModel.owl#49_BA_01_light_sensingService");
    ////        hMap.put("hasTag", "light sensor 49,1st,BA,office");
    //        hMap.put("hasLatitude", new String[]{"51.243455"});
    ////        hMap.put("hasGlobalLocation", "http://www.geonames.org/2647793/");
    ////        hMap.put("hasResourceID", "Resource_53_BA_power_sensor");
    ////        hMap.put("hasLocalLocation", "http://www.surrey.ac.uk/ccsr/ontologies/LocationModel.owl#U49");
    //        hMap.put("hasAltitude", new String[]{""});
    //        hMap.put("hasLongitude", new String[]{"-0.588088"});
    ////        hMap.put("hasTimeOffset", "20");
    //
    //        //ri.ONT_URL = "http://www.surrey.ac.uk/ccsr/ontologies/ServiceModel.owl#";
    //        //ri.ONT_URL = "http://www.surrey.ac.uk/ccsr/ontologies/VirtualEntityModel.owl#";
    //        //ri.ONT_FILE = "web/IoTA-Models/VirtualEntityModel.owl";
    //        ri.createJenaModel(hMap);
}

From source file:net.turnbig.jdbcx.utilities.JsonMapper.java

@SuppressWarnings("deprecation")
public static void main(String[] args) {

    String json = "[{\"asddd\":1}";

    boolean isJson = true;

    try {/*from   w  w  w .ja va  2 s . c o m*/
        ObjectMapper m = new ObjectMapper();
        if (json.trim().startsWith("[")) {
            JavaType typeRef = TypeFactory.defaultInstance().constructParametricType(List.class, Map.class);
            m.readValue(json, typeRef);
        } else {
            JavaType typeRef = TypeFactory.defaultInstance().constructMapType(HashMap.class, String.class,
                    Object.class);
            m.readValue(json, typeRef);
            m.readValue(json, typeRef);
        }
    } catch (Exception e) {
        isJson = false;
    }

    System.out.println(isJson);
}

From source file:it.dontesta.sugarcrm.webservices.client.OAuthSimpleClientTest.java

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

    try {//w ww. j a v  a  2  s .  co m

        final String PROTECTED_ACCOUNTS_RESOURCE_URL = "/Accounts";
        final String PROTECTED_ME_PREFERENCES_RESOURCE_URL = "/me/preferences?oauth_token=";
        final String PROTECTED_METADATA = "/metadata?oauth_token=";

        // Replace these with your own api key and secret
        final String API_KEY = "antonio_musarra_blog";
        final String API_SECRET = "antonio_musarra_blog";
        final String API_USERNAME = "admin";
        final String API_PASSWORD = "Admin2014";
        final String REQUEST_PARAM_DEFAULT_PLATFORM = "platform";

        System.out.println("Try to get Access Token from " + getAccessTokenEndpoint() + "...");

        OAuthClientRequest request = OAuthClientRequest.tokenLocation(getAccessTokenEndpoint())
                .setGrantType(GrantType.PASSWORD).setClientId(API_KEY).setClientSecret(API_SECRET)
                .setUsername(API_USERNAME).setPassword(API_PASSWORD)
                .setParameter(REQUEST_PARAM_DEFAULT_PLATFORM, getPlatform()).buildBodyMessage();

        OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
        OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.accessToken(request);

        System.out.println("Access Token: " + oAuthResponse.getAccessToken() + ", Expires in: "
                + oAuthResponse.getExpiresIn());

        OAuthClientRequest clientRequest = new OAuthClientRequest.AuthenticationRequestBuilder(getFullApiUrl()
                + PROTECTED_ACCOUNTS_RESOURCE_URL + "/" + "c24c4069-7092-b95d-c040-523cc74a3d06")
                        .setParameter(OAuth.OAUTH_TOKEN, oAuthResponse.getAccessToken()).buildQueryMessage();

        System.out.println("Try to request a protected resource: " + clientRequest.getLocationUri());

        OAuthResourceResponse resourceResponse = oAuthClient.resource(clientRequest, OAuth.HttpMethod.GET,
                OAuthResourceResponse.class);

        if (resourceResponse.getResponseCode() == 200) {
            System.out.println("Response is OK. Content of response: ");

            ObjectMapper mapper = new ObjectMapper();
            Account account = mapper.readValue(resourceResponse.getBody(), Account.class);

            System.out.println("####### ACCOUNT OBJECT ########");
            System.out.println("Account Id: " + account.getId());
            System.out.println("Account Name: " + account.getName());
            System.out.println("Account Type: " + account.getAccountType());
            System.out.println("Account Description: " + account.getDescription());
            System.out.println("####### END ACCOUNT OBJECT ########");

            System.out.println("####### ACCOUNT JSON RESPONSE ########");
            System.out.println(new GsonBuilder().setPrettyPrinting().create()
                    .toJson(new JsonParser().parse(resourceResponse.getBody())));
            System.out.println("####### END ACCOUNT JSON RESPONSE ########");
        } else {
            System.err.println("Response is KO with HTTP status code " + resourceResponse.getResponseCode());
            System.err.println(resourceResponse.getBody());
        }

        clientRequest = new OAuthClientRequest.AuthenticationRequestBuilder(
                getFullApiUrl() + PROTECTED_ACCOUNTS_RESOURCE_URL)
                        .setParameter(OAuth.OAUTH_TOKEN, oAuthResponse.getAccessToken()).buildQueryMessage();

        System.out.println("Try to request a protected resource: " + clientRequest.getLocationUri());

        resourceResponse = oAuthClient.resource(clientRequest, OAuth.HttpMethod.GET,
                OAuthResourceResponse.class);

        if (resourceResponse.getResponseCode() == 200) {
            System.out.println("Response is OK. Content of response: ");

            ObjectMapper mapper = new ObjectMapper();
            Accounts accounts = mapper.readValue(resourceResponse.getBody(), Accounts.class);

            System.out.println("####### ACCOUNTS RESPONSE ########");
            for (Account account : accounts.getAccounts()) {
                System.out.println(
                        "Account Name: " + account.getName() + " {Account Id: " + account.getId() + "}");
            }
            System.out.println("####### END ACCOUNTS RESPONSE ########");
        } else {
            System.err.println("Response is KO with HTTP status code " + resourceResponse.getResponseCode());
            System.err.println(resourceResponse.getBody());
        }

        clientRequest = new OAuthClientRequest.AuthenticationRequestBuilder(
                getFullApiUrl() + PROTECTED_ME_PREFERENCES_RESOURCE_URL)
                        .setParameter(OAuth.OAUTH_TOKEN, oAuthResponse.getAccessToken()).buildQueryMessage();

        System.out.println("Try to request a protected resource: " + clientRequest.getLocationUri());

        resourceResponse = oAuthClient.resource(clientRequest, OAuth.HttpMethod.GET,
                OAuthResourceResponse.class);

        if (resourceResponse.getResponseCode() == 200) {
            System.out.println("Response is OK. Content of response: ");

            System.out.println("####### MY PREFERENCES JSON RESPONSE ########");
            System.out.println(new GsonBuilder().setPrettyPrinting().create()
                    .toJson(new JsonParser().parse(resourceResponse.getBody())));
            System.out.println("####### END MY PREFERENCES JSON RESPONSE ########");
        } else {
            System.err.println("Response is KO with HTTP status code " + resourceResponse.getResponseCode());
            System.err.println(resourceResponse.getBody());
        }

        Account newAccountObject = new Account();
        newAccountObject.setName("Antonio Musarra's Blog");
        newAccountObject.setAccountType("Customer");
        newAccountObject.setDescription("New account inserted by java rest client");

        List<Email> emailList = new ArrayList<Email>();
        Email email = new Email();
        email.setEmailAddress("antonio.musarra@shirus.it");
        email.setPrimaryAddress(true);
        emailList.add(email);
        newAccountObject.setEmail(emailList);

        clientRequest = new OAuthClientRequest.AuthenticationRequestBuilder(
                getFullApiUrl() + PROTECTED_ACCOUNTS_RESOURCE_URL)
                        .setParameter(OAuth.OAUTH_TOKEN, oAuthResponse.getAccessToken()).buildQueryMessage();
        clientRequest.setBody(new ObjectMapper().writer().writeValueAsString(newAccountObject));

        System.out.println("Try to request a protected resource: " + clientRequest.getLocationUri());

        resourceResponse = oAuthClient.resource(clientRequest, OAuth.HttpMethod.POST,
                OAuthResourceResponse.class);

        if (resourceResponse.getResponseCode() == 200) {
            System.out.println("Response is OK. Content of response: ");

            ObjectMapper mapper = new ObjectMapper();
            Account account = mapper.readValue(resourceResponse.getBody(), Account.class);

            System.out.println("####### ACCOUNT OBJECT INSERTED ########");
            System.out.println("Account Id: " + account.getId());
            System.out.println("Account Name: " + account.getName());
            System.out.println("Account Type: " + account.getAccountType());
            System.out.println("Account Description: " + account.getDescription());
            System.out.println("####### END ACCOUNT OBJECT INSERTED ########");

            System.out.println("####### ACCOUNT JSON RESPONSE ########");
            System.out.println(new GsonBuilder().setPrettyPrinting().create()
                    .toJson(new JsonParser().parse(resourceResponse.getBody())));
            System.out.println("####### END ACCOUNT JSON RESPONSE ########");
        } else {
            System.err.println("Response is KO with HTTP status code " + resourceResponse.getResponseCode());
            System.err.println(resourceResponse.getBody());
        }

    } catch (OAuthProblemException e) {
        System.out.println("OAuth error: " + e.getError());
        System.out.println("OAuth error description: " + e.getDescription());
    }
}

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

public static void main(String[] args) throws Exception {
    try {/*from  w  w w.  j a va 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());
}