Example usage for com.fasterxml.jackson.dataformat.xml JacksonXmlModule setDefaultUseWrapper

List of usage examples for com.fasterxml.jackson.dataformat.xml JacksonXmlModule setDefaultUseWrapper

Introduction

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

Prototype

public void setDefaultUseWrapper(boolean state) 

Source Link

Document

Method that can be used to define whether AnnotationIntrospector we register will use wrapper for indexed (List, array) properties or not, if there are no explicit annotations.

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  . j a  v a  2s . 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:ru.anr.base.services.serializer.XMLSerializerImpl.java

/**
 * Constructor//from  w w w. jav a  2 s .co  m
 */
public XMLSerializerImpl() {

    super(new XmlMapper());

    JacksonXmlModule module = new JacksonXmlModule();
    module.setDefaultUseWrapper(false);

    mapper().registerModule(module);

    ((XmlMapper) mapper()).configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
}

From source file:com.sysomos.test.SysomosXmlSerDeTest.java

@Before
public void Before() {

    XmlFactory f = new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl());

    JacksonXmlModule module = new JacksonXmlModule();

    module.setDefaultUseWrapper(false);

    xmlMapper = new XmlMapper(f, module);

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

}

From source file:com.kurtraschke.ctatt.gtfsrealtime.services.TrainTrackerDataService.java

@PostConstruct
public void start() {
    _connectionManager = new BasicHttpClientConnectionManager();
    JacksonXmlModule m = new JacksonXmlModule();
    m.setDefaultUseWrapper(false);
    _xmlMapper = new XmlMapper(m);
}

From source file:org.apache.streams.data.moreover.MoreoverResult.java

protected MoreoverResult(String clientId, String xmlString, long start, long end) {
    this.xmlString = xmlString;
    this.clientId = clientId;
    this.start = start;
    this.end = end;
    XmlFactory f = new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl());

    JacksonXmlModule module = new JacksonXmlModule();

    module.setDefaultUseWrapper(false);

    xmlMapper = new XmlMapper(f, module);

    xmlMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
    xmlMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);
    xmlMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, Boolean.TRUE);
    xmlMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, Boolean.TRUE);
    xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);

    mapper = new ObjectMapper();

    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
    mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);
    mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, Boolean.TRUE);
    mapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, Boolean.TRUE);

}

From source file:org.resthub.web.converter.MappingJackson2XmlHttpMessageConverter.java

/**
 * Construct a new {@code BindingJacksonHttpMessageConverter}.
 *//*  ww w  .j a v  a2 s .c  o  m*/
public MappingJackson2XmlHttpMessageConverter() {
    super(new MediaType("application", "xml", DEFAULT_CHARSET));
    JacksonXmlModule xmlModule = new JacksonXmlModule();
    xmlModule.setDefaultUseWrapper(false);
    objectMapper = new XmlMapper(xmlModule);
    SimpleModule module = new SimpleModule();
    module.addAbstractTypeMapping(Page.class, PageResponse.class);
    objectMapper.registerModule(module);
    AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
    objectMapper.setAnnotationIntrospector(introspector);
}

From source file:ninja.utils.XmlMapperProvider.java

@Override
public XmlMapper get() {

    JacksonXmlModule module = new JacksonXmlModule();
    // Check out: https://github.com/FasterXML/jackson-dataformat-xml
    // setDefaultUseWrapper produces more similar output to
    // the Json output. You can change that with annotations in your
    // models.//from  w w  w.jav a2 s.  c  o  m
    module.setDefaultUseWrapper(false);

    XmlMapper xmlMapper = new XmlMapper(module);
    xmlMapper.registerModule(new AfterburnerModule());

    return xmlMapper;

}

From source file:org.doctester.testbrowser.Response.java

public Response(Map<String, String> headers, int httpStatus, String payload) {

    // configure the JacksonXml mapper in a cleaner way...
    JacksonXmlModule module = new JacksonXmlModule();
    // Check out: https://github.com/FasterXML/jackson-dataformat-xml
    // setDefaultUseWrapper produces more similar output to
    // the Json output. You can change that with annotations in your
    // models.//  ww  w . ja v  a  2s. c o  m
    module.setDefaultUseWrapper(false);
    this.xmlMapper = new XmlMapper(module);

    this.objectMapper = new ObjectMapper();

    this.headers = headers;
    this.httpStatus = httpStatus;
    this.payload = payload;

}

From source file:org.jberet.support.io.XmlFactoryObjectFactory.java

/**
 * Gets an instance of {@code com.fasterxml.jackson.dataformat.xml.XmlFactory} based on the resource configuration in the
 * application server. The parameter {@code environment} contains XmlFactory configuration properties, and accepts
 * the following properties:/*from  w w  w.  jav  a2  s  . c om*/
 * <ul>
 * <li>inputDecorator: fully-qualified name of a class that extends {@code com.fasterxml.jackson.core.io.InputDecorator}
 * <li>outputDecorator: fully-qualified name of a class that extends {@code com.fasterxml.jackson.core.io.OutputDecorator}
 * <li>xmlTextElementName: 
 * <li>defaultUseWrapper:
 * </ul>
 *
 * @param obj         the JNDI name of {@code com.fasterxml.jackson.dataformat.xml.XmlFactory} resource
 * @param name        always null
 * @param nameCtx     always null
 * @param environment a {@code Hashtable} of configuration properties
 * @return an instance of {@code com.fasterxml.jackson.dataformat.xml.XmlFactory}
 * @throws Exception any exception occurred
 */
@Override
public Object getObjectInstance(final Object obj, final Name name, final Context nameCtx,
        final Hashtable<?, ?> environment) throws Exception {
    XmlFactory xmlFactory = xmlFactoryCached;
    if (xmlFactory == null) {
        synchronized (this) {
            xmlFactory = xmlFactoryCached;
            if (xmlFactory == null) {
                xmlFactoryCached = xmlFactory = new XmlFactory();
            }

            JacksonXmlModule xmlModule = null;
            NoMappingJsonFactoryObjectFactory.configureInputDecoratorAndOutputDecorator(xmlFactory,
                    environment);

            final Object xmlTextElementName = environment.get("xmlTextElementName");
            if (xmlTextElementName != null) {
                xmlModule = new JacksonXmlModule();
                xmlModule.setXMLTextElementName((String) xmlTextElementName);
            }

            final Object defaultUseWrapper = environment.get("defaultUseWrapper");
            if (defaultUseWrapper != null) {
                if (defaultUseWrapper.equals("false")) {
                    if (xmlModule == null) {
                        xmlModule = new JacksonXmlModule();
                    }
                    xmlModule.setDefaultUseWrapper(false);
                } else if (defaultUseWrapper.equals("true")) {
                    //default value is already true, so nothing to do
                } else {
                    throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, (String) defaultUseWrapper,
                            "defaultUseWrapper");
                }
            }

            final XmlMapper xmlMapper = xmlModule == null ? new XmlMapper(xmlFactory)
                    : new XmlMapper(xmlFactory, xmlModule);
            xmlFactory.setCodec(xmlMapper);
        }
    }
    return xmlFactory;
}