Showing posts with label Unmarshalling. Show all posts
Showing posts with label Unmarshalling. Show all posts

Saturday, 14 September 2019

How to convert an object into XML and XML into an object using JAXB? - BookStore Example

🚀 Master Java Programming with Ram N Java!

Subscribe now for comprehensive tutorials, clear code walkthroughs, and practical Java guides.

🔔 Subscribe to YouTube Channel

What is JAXB? (Java Architecture for XML Binding)

JAXB stands for Java Architecture for XML Binding. It provides a quick and convenient way to bind XML schemas and Java representations, making it easy for Java developers to read and write XML data without needing low-level XML parsers like DOM or SAX.

Key Concepts: Marshalling & Unmarshalling

Working with JAXB revolves around two fundamental operations:

  • Marshalling (Object to XML): The process of serializing a Java object tree into an XML document or stream.
  • Unmarshalling (XML to Object): The process of deserializing XML data back into a structured Java object.

Essential JAXB Annotations

To map your Java classes to XML structures, JAXB uses simple annotations:

  • @XmlRootElement: Defines the top-level root element of the XML document.
  • @XmlElement: Maps a Java field or getter/setter to an XML child tag.
  • @XmlAttribute: Maps a field as an attribute within an XML element.
  • @XmlElementWrapper: Generates a wrapper XML element around collection elements (such as a list of books).

Step-by-Step BookStore Example

1. Define the Book & BookStore Classes

Create your POJO classes and annotate them so JAXB knows how to convert the properties:

@XmlRootElement(name = "bookstore")
public class BookStore {
    private String name;
    private List<Book> bookList;

    @XmlElement(name = "name")
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    @XmlElementWrapper(name = "bookList")
    @XmlElement(name = "book")
    public List<Book> getBookList() { return bookList; }
    public void setBookList(List<Book> bookList) { this.bookList = bookList; }
}

2. Marshalling: Converting Java Object to XML

JAXBContext context = JAXBContext.newInstance(BookStore.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

// Write to console or file
marshaller.marshal(bookStore, System.out);

3. Unmarshalling: Converting XML to Java Object

JAXBContext context = JAXBContext.newInstance(BookStore.class);
Unmarshaller unmarshaller = context.createUnmarshaller();

BookStore bookStore = (BookStore) unmarshaller.unmarshal(new File("bookstore.xml"));
System.out.println("Store Name: " + bookStore.getName());

Recommended Java Tutorials from Ram N Java

How to convert an object into XML and XML into object using JAXB? - Employee Example | JAXB Tutorial

💡 Level Up Your Java Skills with Ram N Java!

Subscribe now for clear explanations, practical coding demos, and end-to-end tutorials.

🔔 Subscribe to YouTube Channel

Introduction to JAXB

JAXB (Java Architecture for XML Binding) provides a simple and clean API to convert Java objects into XML documents and vice versa. It removes the need for tedious manual parsing with DOM or SAX.

Core Operations in JAXB

  • Marshalling: Converting a Java object representation into an XML file or stream.
  • Unmarshalling: Reading an XML file or stream and converting it back into a Java object.

Annotations Used in Employee Example

  • @XmlRootElement: Specifies that the Employee class represents the root element in the generated XML.
  • @XmlAttribute: Configures a property (like id) to appear as an attribute of the XML root tag.
  • @XmlElement: Maps class fields (like name and salary) to child elements within the XML.

Step-by-Step Code Walkthrough

1. Annotated Employee Class

@XmlRootElement(name = "employee")
public class Employee {
    private int id;
    private String name;
    private double salary;

    public Employee() {}

    public Employee(int id, String name, double salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }

    @XmlAttribute(name = "id")
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    @XmlElement(name = "name")
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    @XmlElement(name = "salary")
    public double getSalary() { return salary; }
    public void setSalary(double salary) { this.salary = salary; }
}

2. Marshalling: Java Object to XML

JAXBContext context = JAXBContext.newInstance(Employee.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

Employee emp = new Employee(1, "Peter", 50000);
FileOutputStream fos = new FileOutputStream("employee.xml");
marshaller.marshal(emp, fos);
fos.close();

3. Unmarshalling: XML to Java Object

JAXBContext context = JAXBContext.newInstance(Employee.class);
Unmarshaller unmarshaller = context.createUnmarshaller();

File xmlFile = new File("employee.xml");
Employee emp = (Employee) unmarshaller.unmarshal(xmlFile);
System.out.println(emp);

Related Tutorials from Ram N Java

Monday, 28 January 2019

Spring and Xstream Integration | Spring Object/XML Mapping | jaxb marshalling and unmarshalling

🚀 Boost Your Spring & Java Skills with Ram N Java!

Subscribe today for practical coding guides, framework integrations, and clean Java tutorials.

🔔 Subscribe to YouTube Channel

What is Spring OXM and XStream?

Spring OXM (Object/XML Mapping) provides an abstraction layer that simplifies converting Java objects to XML and vice versa. XStream is a lightweight, easy-to-use library that enables XML serialization and deserialization without requiring any complex mapping files or schema generation.

Key Concepts: Marshalling & Unmarshalling

  • Marshalling: Serializing a Java object (e.g., a Company object) into an XML format.
  • Unmarshalling: Deserializing XML data back into a structured Java object.

Maven Dependencies

Add the necessary Spring OXM and XStream dependencies to your pom.xml file:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-oxm</artifactId>
    <version>5.3.x</version>
</dependency>
<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.4.x</version>
</dependency>

Step-by-Step Implementation

1. Define the Java Model (Company Class)

public class Company {
    private int id;
    private String companyName;
    private String ceoName;
    private int numberOfEmployees;

    // Getters and Setters
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getCompanyName() { return companyName; }
    public void setCompanyName(String companyName) { this.companyName = companyName; }

    public String getCeoName() { return ceoName; }
    public void setCeoName(String ceoName) { this.ceoName = ceoName; }

    public int getNumberOfEmployees() { return numberOfEmployees; }
    public void setNumberOfEmployees(int numberOfEmployees) { this.numberOfEmployees = numberOfEmployees; }
}

2. Configure Spring XML Configuration

<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
    <property name="aliases">
        <map>
            <entry key="company" value="com.ram.model.Company"/>
        </map>
    </property>
</bean>

3. Marshalling & Unmarshalling Execution

ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
Marshaller marshaller = (Marshaller) context.getBean("xstreamMarshaller");
Unmarshaller unmarshaller = (Unmarshaller) context.getBean("xstreamMarshaller");

// Convert Object to XML
Company company = new Company();
company.setId(101);
company.setCompanyName("Tech Corp");
company.setCeoName("Alice");
company.setNumberOfEmployees(500);

marshaller.marshal(company, new StreamResult(new FileOutputStream("company.xml")));

// Convert XML to Object
Company resultCompany = (Company) unmarshaller.unmarshal(new StreamSource(new FileInputStream("company.xml")));
System.out.println("Company: " + resultCompany.getCompanyName());

Related Tutorials from Ram N Java


Click here to watch on Youtube:
https://www.youtube.com/watch?v=MuqMAnjHAxM&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge:

Spring and Xstream Integration | Spring Object/XML Mapping | jaxb marshalling and unmarshalling

Spring and Xstream Integration | Spring Object/XML Mapping | jaxb marshalling and unmarshalling

Spring and Xstream Integration | Spring Object/XML Mapping | jaxb marshalling and unmarshalling

Spring and Xstream Integration | Spring Object/XML Mapping | jaxb marshalling and unmarshalling

Spring and Xstream Integration | Spring Object/XML Mapping | jaxb marshalling and unmarshalling

Spring and Xstream Integration | Spring Object/XML Mapping | jaxb marshalling and unmarshalling
pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ram.core</groupId>
    <artifactId>SpringDemo</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringDemo</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>5.1.1.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream -->
        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.10</version>
        </dependency>


    </dependencies>
</project>

Company.java

package com.ram.core.model;

public class Company
{
    private Integer id;

    private String companyName;

    private String ceoName;

    private Integer numberOfEmployees;

    public Integer getId()
    {
        return id;
    }

    public void setId(Integer id)
    {
        this.id = id;
     
    }

    public String getCompanyName()
    {
        return companyName;
    }

    public void setCompanyName(String companyName)
    {
        this.companyName = companyName;
    }

    public String getCeoName()
    {
        return ceoName;
    }

    public void setCeoName(String ceoName)
    {
        this.ceoName = ceoName;
    }

    public Integer getNumberOfEmployees()
    {
        return numberOfEmployees;
    }

    public void setNumberOfEmployees(Integer numberOfEmployees)
    {
        this.numberOfEmployees = numberOfEmployees;
    }

    @Override
    public String toString()
    {
        return "Company [id=" + id + ", companyName=" + companyName
                + ", ceoName=" + ceoName + ", numberOfEmployees="
                + numberOfEmployees + "]";
    }

}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">



    <bean id="xstreamMarshallerBean"
        class="org.springframework.oxm.xstream.XStreamMarshaller">
     
        <property name="annotatedClasses"
            value="com.ram.core.model.Company"></property>
         
    </bean>

</beans>

App.java

package com.ram.core;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

import com.ram.core.model.Company;

public class App
{

    public static void main(String[] args) throws IOException
    {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");

        convertObjectToXML(context);
        convertXMLToObject(context);
    }

    private static void convertObjectToXML(ApplicationContext context)
            throws IOException
    {
        Marshaller marshaller = (Marshaller) context
                .getBean("xstreamMarshallerBean");

        // Perform Marshaling
        Company company = new Company();
        company.setId(201);
        company.setCompanyName("Google");
        company.setCeoName("Peter");
        company.setNumberOfEmployees(50000);

        marshaller.marshal(company,
                new StreamResult(new FileWriter("company.xml")));

        System.out.println("XML Created Sucessfully");
    }
 
    private static void convertXMLToObject(ApplicationContext context)
            throws FileNotFoundException, IOException
    {
        Unmarshaller unmarshaller = (Unmarshaller) context
                .getBean("xstreamMarshallerBean");   
     
        FileInputStream is = null;
        try
        {
            is = new FileInputStream("company.xml");
            Object object = unmarshaller.unmarshal(new StreamSource(is));
            System.out.println(object);
            System.out.println("Converted XML to Object!");
        }
        finally
        {
            if (is != null)
            {
                is.close();
            }
        }
    }

 
}

Output:

XML Created Sucessfully
Security framework of XStream not initialized, XStream is probably vulnerable.
Company [id=201, companyName=Google, ceoName=Peter, numberOfEmployees=50000]
Converted XML to Object!

company.xml

<com.ram.core.model.Company><id>201</id><companyName>Google</companyName><ceoName>Peter</ceoName><numberOfEmployees>50000</numberOfEmployees></com.ram.core.model.Company>

Click the below link to download the code:
https://sites.google.com/site/javaspringram2019/java_spring_2019/SpringDemo_Xtream_Integration.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java_Spring_2019/tree/master/Spring_2019/SpringDemo_Xtream_Integration

Bitbucket Link:
https://bitbucket.org/ramram43210/java_spring_2019/src/2db5cd1f4e7d5ab55ad7af886d6164700143c614/Spring_2019/SpringDemo_Xtream_Integration/?at=master

See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • Spring and JAXB Integration | Spring Object/XML Mapping | jaxb marshalling and unmarshalling

    🚀 Master Spring & Java with Ram N Java!

    Subscribe today for practical Spring frameworks, OXM mappings, and clear Java tutorials.

    🔔 Subscribe to YouTube Channel

    Overview: Spring OXM with JAXB

    Spring's Object/XML Mapping (OXM) framework simplifies XML binding by providing unified abstractions via Marshaller and Unmarshaller interfaces. Integrating Spring with JAXB (Java Architecture for XML Binding) enables seamless conversion between Java objects and XML documents with minimal configuration.

    Key Concepts

    • Marshalling: Converting a Java object graph into an XML representation.
    • Unmarshalling: Parsing an XML document and instantiating corresponding Java objects.
    • Jaxb2Marshaller: The central Spring OXM class that implements both Spring's Marshaller and Unmarshaller interfaces.

    Step-by-Step Implementation

    1. Define the JAXB Annotated Model Class

    @XmlRootElement(name = "customer")
    public class Customer {
        private int id;
        private String name;
        private int age;
    
        @XmlAttribute(name = "id")
        public int getId() { return id; }
        public void setId(int id) { this.id = id; }
    
        @XmlElement(name = "name")
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
    
        @XmlElement(name = "age")
        public int getAge() { return age; }
        public void setAge(int age) { this.age = age; }
    }

    2. Configure Spring Jaxb2Marshaller

    Configure the Spring bean definition to bind the target classes to be bound:

    <bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="classesToBeBound">
            <list>
                <value>com.ram.model.Customer</value>
            </list>
        </property>
    </bean>

    3. Marshalling and Unmarshalling via Spring

    ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
    Jaxb2Marshaller marshaller = (Jaxb2Marshaller) context.getBean("jaxb2Marshaller");
    
    // 1. Marshalling (Object to XML)
    Customer customer = new Customer();
    customer.setId(101);
    customer.setName("John Doe");
    customer.setAge(30);
    
    marshaller.marshal(customer, new StreamResult(new FileOutputStream("customer.xml")));
    
    // 2. Unmarshalling (XML to Object)
    Customer unmarshalledCustomer = (Customer) marshaller.unmarshal(new StreamSource(new FileInputStream("customer.xml")));
    System.out.println("Customer Name: " + unmarshalledCustomer.getName());

    Related Tutorials from Ram N Java


    Click here to watch on Youtube:
    https://www.youtube.com/watch?v=DPZjhK66cE4&index=11&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge:
    Spring and JAXB Integration | Spring Object/XML Mapping | jaxb marshalling and unmarshalling

    Spring and JAXB Integration | Spring Object/XML Mapping | jaxb marshalling and unmarshalling

    Spring and JAXB Integration | Spring Object/XML Mapping | jaxb marshalling and unmarshalling

    Spring and JAXB Integration | Spring Object/XML Mapping | jaxb marshalling and unmarshalling

    Spring and JAXB Integration | Spring Object/XML Mapping | jaxb marshalling and unmarshalling

    pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.ram.core</groupId>
        <artifactId>SpringDemo</artifactId>
        <packaging>jar</packaging>
        <version>1.0-SNAPSHOT</version>
        <name>SpringDemo</name>
        <url>http://maven.apache.org</url>

        <properties>
            <spring.version>5.1.1.RELEASE</spring.version>
        </properties>

        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.8.2</version>
                <scope>test</scope>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>


            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-oxm</artifactId>
                <version>${spring.version}</version>
            </dependency>
        </dependencies>
    </project>

    Company.java

    package com.ram.core.model;

    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlAttribute;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;

    @XmlRootElement(name = "CompanyInfo", namespace = "com.ram.core")
    @XmlAccessorType(XmlAccessType.NONE)
    public class Company
    {
        @XmlAttribute(name = "Id")
        private Integer id;

        @XmlElement(name = "CompanyName")
        private String companyName;

        @XmlElement(name = "CEO_Name")
        private String ceoName;

        @XmlElement(name = "Number_Of_Employees")
        private Integer numberOfEmployees;

        public Integer getId()
        {
            return id;
        }

        public void setId(Integer id)
        {
            this.id = id;
        }

        public String getCompanyName()
        {
            return companyName;
        }

        public void setCompanyName(String companyName)
        {
            this.companyName = companyName;
        }

        public String getCeoName()
        {
            return ceoName;
        }

        public void setCeoName(String ceoName)
        {
            this.ceoName = ceoName;
        }

        public Integer getNumberOfEmployees()
        {
            return numberOfEmployees;
        }

        public void setNumberOfEmployees(Integer numberOfEmployees)
        {
            this.numberOfEmployees = numberOfEmployees;
        }

        @Override
        public String toString()
        {
            return "Company [id=" + id + ", companyName=" + companyName
                    + ", ceoName=" + ceoName + ", numberOfEmployees="
                    + numberOfEmployees + "]";
        }

    }

    applicationContext.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:oxm="http://www.springframework.org/schema/oxm"
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd  
       http://www.springframework.org/schema/oxm  
       http://www.springframework.org/schema/oxm/spring-oxm-4.3.xsd">


        <oxm:jaxb2-marshaller id="jaxbMarshallerBean">
            <oxm:class-to-be-bound
                name="com.ram.core.model.Company" />
        </oxm:jaxb2-marshaller>

    </beans>

    App.java

    package com.ram.core;

    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;

    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.stream.StreamSource;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.oxm.Marshaller;
    import org.springframework.oxm.Unmarshaller;

    import com.ram.core.model.Company;

    public class App
    {

        public static void main(String[] args) throws IOException
        {
            ApplicationContext context = new ClassPathXmlApplicationContext(
                    "applicationContext.xml");
            Marshaller marshaller = (Marshaller) context
                    .getBean("jaxbMarshallerBean");

            Unmarshaller unmarshaller = (Unmarshaller) context
                    .getBean("jaxbMarshallerBean");
         
            Company company = new Company();
            company.setId(201);
            company.setCompanyName("Google");
            company.setCeoName("Peter");
            company.setNumberOfEmployees(50000);

            // Perform Marshaling
            marshaller.marshal(company,
                    new StreamResult(new FileWriter("company.xml")));

            System.out.println("XML Created Sucessfully");

            // Perform Unmarshaling
            Company company2 = (Company) unmarshaller
                    .unmarshal(new StreamSource(new FileReader("company.xml")));
            System.out.println(company2);
            System.out.println("Converted XML to Object!");

        }
    }

    Output:

    XML Created Sucessfully
    Company [id=201, companyName=Google, ceoName=Peter, numberOfEmployees=50000]
    Converted XML to Object!

    company.xml

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?><ns2:CompanyInfo Id="201" xmlns:ns2="com.ram.core"><CompanyName>Google</CompanyName><CEO_Name>Peter</CEO_Name><Number_Of_Employees>50000</Number_Of_Employees></ns2:CompanyInfo>

    Click the below link to download the code:
    https://sites.google.com/site/javaspringram2019/java_spring_2019/SpringDemo_Spring_Jaxb_Integration.zip?attredirects=0&d=1

    Github Link:
    https://github.com/ramram43210/Java_Spring_2019/tree/master/Spring_2019/SpringDemo_Spring_Jaxb_Integration

    Bitbucket Link:
    https://bitbucket.org/ramram43210/java_spring_2019/src/2db5cd1f4e7d5ab55ad7af886d6164700143c614/Spring_2019/SpringDemo_Spring_Jaxb_Integration/?at=master

    See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • Tutorials