JAXB annotation "Go"

Source: Internet
Author: User
Tags map class

http://blog.csdn.net/lw371496536/article/details/6942045

JAXB (Java API for XML Binding) provides a quick and easy way to convert Java objects to and from XML. In Jax-WS (One of Java's WebService specifications), JDK1.6 comes with version jax-ws2.1, with the underlying support being JAXB.

JAXB can implement the conversion of Java objects to XML, in JAXB, the process of converting a Java object to XML is called Marshal, and the process of converting XML to a Java object is called Unmarshal. We can bind a Java object to a piece of XML by annotating it in a Java class, that is, annotating the Java class with annotations that define how the class is converted to XML, how it is transformed, and how an XML is parsed into the object defined by the class. You can also use JAXB's XJC tool to define the schema to bind Java objects to XML (this next study).

Here's a look at how to complete the Marshal and unmarshal process by annotating annotations. I use Jaxb2_20101209.jar, I can download the latest version to http://jaxb.java.net/.

First look at a small example:



Define a Java class

Java code
Package COM.WHY.JAXB;

Import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class People {
Public String id = "001";
Public String name = "Grey too Wolf";
public int age = 26;
}

We generally add related annotations on the Get method in practice
Java to XML (Marshal)

Java code
Package COM.WHY.JAXB;

Import Javax.xml.bind.JAXBContext;
Import javax.xml.bind.JAXBException;
Import Javax.xml.bind.Marshaller;

public class Java2xml {

/**
* @param args
* @throws jaxbexception
*/
public static void Main (string[] args) throws Jaxbexception {
Jaxbcontext context = jaxbcontext.newinstance (People.class);

Marshaller Marshaller = Context.createmarshaller ();
Marshaller.setproperty (marshaller.jaxb_encoding, "gb2312");//Encoding format

I have re-encapsulated the JAXB base class in real-world development, and this property is used here. However, the default encoding format UTF-8

Marshaller.setproperty (Marshaller.jaxb_formatted_output, true);//whether to format the generated XML string
Marshaller.setproperty (Marshaller.jaxb_fragment, false);//whether to omit the XML header information (<?xml version= "1.0" encoding= "gb2312" Standalone= "yes"?>)

People people = new people ();
Marshaller.marshal (people, System.out);
}

}

XML to Java (unmarshal)

Java code
Package COM.WHY.JAXB;

Import Java.io.File;
Import Javax.xml.bind.JAXBContext;
Import javax.xml.bind.JAXBException;
Import Javax.xml.bind.Unmarshaller;
Import org.xml.sax.SAXException;

public class Xml2java {
/**
* @param args
* @throws jaxbexception
* @throws jaxbexception
* @throws saxexception
*/
public static void Main (string[] args) throws Jaxbexception {
Jaxbcontext context = jaxbcontext.newinstance (People.class);
Unmarshaller Unmarshaller = Context.createunmarshaller ();
File File = new file ("Src/people.xml");
People people = (people) Unmarshaller.unmarshal (file);
System.out.println (people.id);
System.out.println (People.name);
System.out.println (People.age);
}
}

In fact, marshal and unmarshal process is not complicated, only need to get Marshaller or Unmarshaller object from Jaxbcontext, you can let JAXB help us to convert. The main things we need to do is to define a rule that tells Jaxb how to convert a class, to what format, to XML, and here are some of the main annotations in JAXB.



@XmlRootElement Map a Java class to the root node of an XML

Parameters: Name defines the names of this root node

namespace defines this root node namespace



@XmlAccessorType define what types of mappings in this class need to be mapped to XML. Can receive four parameters, respectively:

Xmlaccesstype.field: Mapping All fields in this class to XML

Xmlaccesstype.property: Mapping properties in this class (Get/set method) to XML

Xmlaccesstype.public_member: Maps the field or property of all public in this class to XML at the same time (default)

Xmlaccesstype.none: Not mapped



@XmlElement a node that specifies a field or Get/set method to map to XML. For example, when a class's xmlaccessortype is labeled as a property, the annotation is annotated on a field that does not have a Get/set method, and the field can be mapped to XML.

Parameter: DefaultValue specify node default value

Name specifies the node name

Namespace specifying a node namespace

Whether the required must be (false by default)

nillable Whether the field contains a nillable= "true" property (False by default)

Type defines the association types for this field or property



@XmlAttribute Specify a field or Get/set method to map to the attributes of the XML.

Parameter: name Specifies the property name

Namespace specifying a property namespace

Whether the required must be (false by default)



@XmlTransient Define a field or property that does not need to be mapped to XML. For example, when a class's xmlaccessortype is labeled as a property, the annotation is annotated on the field of a Get/set method, and the attribute is not mapped.



@XmlType some related rules for defining mappings

Parameter: proporder Specifies the order of nodes when mapping XML

FACTORYCLASS Specifies the factory class required to generate the Map class instance when Unmarshal is specified, which defaults to the class itself

FactoryMethod factory methods for specifying factory classes

Name defines the names of the type in the XML Schema

Namespace specifying namespaces in the schema



@XmlElementWrapper define a parent node for an array element or collection element. For example, an element in a class is a list items, and if you do not add this annotation, the element is mapped to

<items>...</items>

<items>...</items>

This form, this annotation can be wrapped in this element, such as:

@XmlElementWrapper (name= "items")
@XmlElement (name= "item")
public List items;

Such an XML style will be generated:

<items>

<item>...</item>

<item>...</item>

</items>



@XmlJavaTypeAdapter customize an adapter that maps a field or property to XML. For example, if a class contains an interface, we can define an adapter (inherited from the Javax.xml.bind.annotation.adapters.XmlAdapter Class) to specify how the interface maps to XML.



@XmlSchema Configure the namespace of the entire package, this annotation needs to be placed in the Package-info.java file.

JAXB Encoding:

Jaxbcontext Jaxbcontext = jaxbcontext.newinstance (clazz);
Unmarshaller Unmarshaller = Jaxbcontext.createunmarshaller ();
InputStreamReader reader=new InputStreamReader (InputStream, "GBK"); Modify the encoding here
return Unmarshaller.unmarshal (reader);

JAXB annotation "Go"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.