Example usage for com.fasterxml.jackson.dataformat.xml XmlMapper readValue

List of usage examples for com.fasterxml.jackson.dataformat.xml XmlMapper readValue

Introduction

In this page you can find the example usage for com.fasterxml.jackson.dataformat.xml XmlMapper readValue.

Prototype

@Override
@SuppressWarnings("unchecked")
public <T> T readValue(JsonParser jp, Class<T> valueType)
        throws IOException, JsonParseException, JsonMappingException 

Source Link

Document

Method to deserialize JSON content into a non-container type (it can be an array type, however): typically a bean, array or a wrapper type (like java.lang.Boolean ).

Usage

From source file:edu.usf.cutr.siri.SiriParserJacksonExample.java

/**
 * Takes in a path to a JSON or XML file, parses the contents into a Siri object, 
 * and prints out the contents of the Siri object.
 * //from ww w.ja  v  a2s.c  o m
 * @param args path to the JSON or XML file located on disk
 */
public static void main(String[] args) {

    if (args[0] == null) {
        System.out.println("Proper Usage is: java JacksonSiriParserExample path-to-siri-file-to-parse");
        System.exit(0);
    }

    try {

        //Siri object we're going to instantiate based on JSON or XML data
        Siri siri = null;

        //Get example JSON or XML from file
        File file = new File(args[0]);

        System.out.println("Input file = " + file.getAbsolutePath());

        /*
         * Alternately, instead of passing in a File, a String encoded in JSON or XML can be
         * passed into Jackson for parsing.  Uncomment the below line to read the 
         * JSON or XML into the String.
         */
        //String inputExample = readFile(file);   

        String extension = FilenameUtils.getExtension(args[0]);

        if (extension.equalsIgnoreCase("json")) {
            System.out.println("Parsing JSON...");
            ObjectMapper mapper = null;

            try {
                mapper = (ObjectMapper) SiriUtils.readFromCache(SiriUtils.OBJECT_MAPPER);
            } catch (Exception e) {
                System.out.println("Error reading from cache: " + e);
            }

            if (mapper == null) {
                // instantiate ObjectMapper like normal if cache read failed
                mapper = new ObjectMapper();

                //Jackson 2.0 configuration settings
                mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
                mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
                mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
                mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
                mapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);

                //Tell Jackson to expect the JSON in PascalCase, instead of camelCase
                mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.PascalCaseStrategy());
            }

            //Deserialize the JSON from the file into the Siri object
            siri = mapper.readValue(file, Siri.class);

            /*
             * Alternately, you can also deserialize the JSON from a String into the Siri object.
             * Uncomment the below line to parsing the JSON from a String instead of the File.
             */
            //siri = mapper.readValue(inputExample, Siri.class);

            //Write the ObjectMapper to the cache, to speed up parsing for the next execution
            SiriUtils.forceCacheWrite(mapper);

        }

        if (extension.equalsIgnoreCase("xml")) {
            System.out.println("Parsing XML...");
            //Use Aalto StAX implementation explicitly            
            XmlFactory f = new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl());

            JacksonXmlModule module = new JacksonXmlModule();

            /**
             * Tell Jackson that Lists are using "unwrapped" style (i.e., 
             * there is no wrapper element for list). This fixes the error
             * "com.fasterxml.jackson.databind.JsonMappingException: Can not
             * >> instantiate value of type [simple type, class >>
             * uk.org.siri.siri.VehicleMonitoringDelivery] from JSON String;
             * no >> single-String constructor/factory method (through
             * reference chain: >>
             * uk.org.siri.siri.Siri["ServiceDelivery"]->
             * uk.org.siri.siri.ServiceDel >>
             * ivery["VehicleMonitoringDelivery"])"
             * 
             * NOTE - This requires Jackson v2.1
             */
            module.setDefaultUseWrapper(false);

            /**
             * Handles "xml:lang" attribute, which is used in SIRI
             * NaturalLanguage String, and looks like: <Description
             * xml:lang="EN">b/d 1:00pm until f/n. loc al and express buses
             * run w/delays & detours. POTUS visit in MANH. Allow additional
             * travel time Details at www.mta.info</Description>
             * 
             * Passing "Value" (to match expected name in XML to map,
             * considering naming strategy) will make things work. This is
             * since JAXB uses pseudo-property name of "value" for XML Text
             * segments, whereas Jackson by default uses "" (to avoid name
             * collisions).
             * 
             * NOTE - This requires Jackson v2.1
             * 
             * NOTE - This still requires a CustomPascalCaseStrategy to
             * work. Please see the CustomPascalCaseStrategy in this app
             * that is used below.
             */
            module.setXMLTextElementName("Value");

            XmlMapper xmlMapper = null;

            try {
                xmlMapper = (XmlMapper) SiriUtils.readFromCache(SiriUtils.XML_MAPPER);
            } catch (Exception e) {
                System.out.println("Error reading from cache: " + e);
            }

            if (xmlMapper == null) {
                xmlMapper = new XmlMapper(f, module);

                xmlMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
                xmlMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
                xmlMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
                xmlMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);

                /**
                 * Tell Jackson to expect the XML in PascalCase, instead of camelCase
                 * NOTE:  We need the CustomPascalStrategy here to handle XML 
                 * namespace attributes such as xml:lang.  See the comments in 
                 * CustomPascalStrategy for details.
                 */
                xmlMapper.setPropertyNamingStrategy(new CustomPascalCaseStrategy());
            }

            //Parse the SIRI XML response            
            siri = xmlMapper.readValue(file, Siri.class);

            //Write the XmlMapper to the cache, to speed up parsing for the next execution
            SiriUtils.forceCacheWrite(xmlMapper);
        }

        //If we successfully retrieved and parsed JSON or XML, print the contents
        if (siri != null) {
            SiriUtils.printContents(siri);
        }

    } catch (IOException e) {
        System.err.println("Error reading or parsing input file: " + e);
    }

}

From source file:uk.ac.kcl.Transform23.java

public static String convertHL7ToJson(Message message) {
    try {//ww w  .j  a v a 2 s . com
        DefaultXMLParser xmlParser = new DefaultXMLParser(new CanonicalModelClassFactory("2.4"));
        Document xml = xmlParser.encodeDocument(message);
        cleanFieldNames(xml.getChildNodes().item(0));
        XmlMapper xmlMapper = new XmlMapper();
        List entries = null;
        try {
            entries = xmlMapper.readValue(getStringFromDocument(xml), List.class);
        } catch (IOException | TransformerException ex) {
            Logger.getLogger(Transform23.class.getName()).log(Level.SEVERE, null, ex);
        }

        ObjectMapper jsonMapper = new ObjectMapper();

        String json = null;
        try {
            json = jsonMapper.writeValueAsString(entries);
        } catch (IOException ex) {
            Logger.getLogger(Transform23.class.getName()).log(Level.SEVERE, null, ex);
        }

        //System.out.println(json);
        json = json.substring(1, (json.length() - 1));
        //to do  - add code to rename fields, removing periods

        return json;
    } catch (HL7Exception ex) {
        Logger.getLogger(Transform23.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:uk.ac.kcl.Transform231.java

public static String convertHL7ToJson(Message message) {
    try {/*  w  w  w  .  ja  va 2s. c  o  m*/
        DefaultXMLParser xmlParser = new DefaultXMLParser(new CanonicalModelClassFactory("2.4"));
        Document xml = xmlParser.encodeDocument(message);
        cleanFieldNames(xml.getChildNodes().item(0));
        XmlMapper xmlMapper = new XmlMapper();
        List entries = null;
        try {
            entries = xmlMapper.readValue(getStringFromDocument(xml), List.class);
        } catch (IOException | TransformerException ex) {
            Logger.getLogger(Transform231.class.getName()).log(Level.SEVERE, null, ex);
        }

        ObjectMapper jsonMapper = new ObjectMapper();

        String json = null;
        try {
            json = jsonMapper.writeValueAsString(entries);
        } catch (IOException ex) {
            Logger.getLogger(Transform231.class.getName()).log(Level.SEVERE, null, ex);
        }

        //System.out.println(json);
        json = json.substring(1, (json.length() - 1));
        //to do  - add code to rename fields, removing periods

        return json;
    } catch (HL7Exception ex) {
        Logger.getLogger(Transform231.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.msopentech.odatajclient.engine.data.Deserializer.java

private static XMLODataError toODataErrorFromXML(final InputStream input) {
    try {//from  www .ja v a2  s .c  o  m
        final XmlMapper xmlMapper = new XmlMapper(
                new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl()), new JacksonXmlModule());
        return xmlMapper.readValue(input, XMLODataError.class);
    } catch (Exception e) {
        throw new IllegalArgumentException("While deserializing XML error", e);
    }
}

From source file:com.tickaroo.jackson.small.JacksonSmallXmlBenchmark.java

public void parse(String xml) throws Exception {
    XmlMapper mapper = new XmlMapper();
    Employee employee = mapper.readValue(xml, Employee.class);
    System.out.println(getClass().getSimpleName() + " " + employee.name);
}

From source file:com.tickaroo.jackson.medium.JacksonMediumXmlBenchmark.java

public void parse(String xml) throws Exception {
    XmlMapper mapper = new XmlMapper();
    Feed feed = mapper.readValue(xml, Feed.class);
    System.out.println(getClass().getSimpleName() + " " + feed);
}

From source file:org.sakaiproject.serialization.BasicSerializableRepository.java

@Override
public T fromXML(String xml) {
    T obj = null;//from  ww w . j  a va 2s  .c o m
    if (StringUtils.isNotBlank(xml)) {
        XmlMapper mapper = new XmlMapper();
        try {
            obj = mapper.readValue(xml, getDomainClass());
        } catch (IOException e) {
            log.warn("Could not deserialize xml", e);
            obj = null;
        }
    }
    return obj;
}

From source file:org.glukit.dexcom.sync.responses.ManufacturingDataDatabasePagesResponse.java

public List<ManufacturingParameters> getManufacturingParameters() {
    List<ManufacturingParameters> manufacturingParameters = newArrayList();
    try {/*  w w w .j av  a  2  s. c o m*/
        for (DatabasePage page : getPages()) {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(page.getPageData());
            DataInput input = this.dataInputFactory.create(inputStream);
            // TODO: something better than ignoring the data?
            long systemSeconds = UnsignedInts.toLong(input.readInt());
            long displaySeconds = UnsignedInts.toLong(input.readInt());

            byte[] xmlBytes = new byte[inputStream.available() - 2];
            input.readFully(xmlBytes);

            validateCrc(input.readUnsignedShort(), page.getPageData());

            XmlMapper xmlMapper = new XmlMapper();
            ManufacturingParameters parameterPage = xmlMapper.readValue(new String(xmlBytes, "UTF-8"),
                    ManufacturingParameters.class);
            manufacturingParameters.add(parameterPage);
        }
        return manufacturingParameters;
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.blockwithme.lessobjects.util.JSONParser.java

/**
 * To json string.// w w  w .  j a va  2s . com
 *
 * @return the string
 */
@SuppressWarnings("null")
public String toJSONString() {

    if (jsonString == null) {
        if (fromSchema) {
            try {
                final ObjectWriter writer = initMapper();
                jsonString = writer.writeValueAsString(schema);
            } catch (final JsonProcessingException jpe) {
                throw new IllegalStateException(jpe.getMessage(), jpe);
            }
        } else {
            try {
                if (format == SchemaFormat.JSON) {
                    jsonString = jsonOrXMLString;
                } else {
                    if (xmlString == null) {
                        xmlString = jsonOrXMLString;
                    }
                    final XmlMapper xmlMapper = new XmlMapper();
                    schema = xmlMapper.readValue(jsonOrXMLString, StructSchema.class);
                    final ObjectMapper jsonMapper = new ObjectMapper();
                    jsonString = jsonMapper.writeValueAsString(schema);
                }
            } catch (final IOException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
        }
    }
    return jsonString;
}