출처 : http://www.caucho.com/resin-3.1/doc/jaxb-annotations.xtp
JAXB annotations customize the serialization of a model bean. @XmlAccessorType@XmlAccessorType sets default field and property serializability. By default, JAXB serializes public fields and properties. By setting @XmlAccessorType, the bean can choose to only allow annotated fields to be serialized. @XmlAccessorType works with the other annotations and @XmlTransient to serialize fields and properties. @XmlTransient prevents serialization, overriding the @XmlAccessorType. The presense of any other annotation will force serialization, overriding the @XmlAccessorType.
@XmlAccessorType serializing fields
@XmlAccessorType(XmlAccessType.FIELD)
class Bean {
private String data;
}
XML Document
<Bean> <data>Sample Data</data> </Bean> @XmlAccessorType
@Target(value={PACKAGE,TYPE})
public @interface XmlAccessorType {
public XmlAccessType value() default XmlAccessType.PUBLIC_MEMBER;
}
XmlAccessType
public enum XmlAccessType {
FIELD, NONE, PROPERTY, PUBLIC_MEMBER;
}
@XmlAttribute@XmlAttribute marks a field or property as serialized to an XML attribute. By default, fields serialize to XML elements. It can also customize the XML attribute name and namespace. @XmlAttribute can work with @XmlAccessorType to select which fields and properties should be serialized to XML. By default, public fields and properties will be serialized. Adding @XmlAttribute to a private field will mark that field as serializable. @XmlAttribute can also customize the XML attribute name. By default, the XML attribute name is taken from the field name or the property name. The @XmlAttribute for a private field
@XmlRootElement
class Bean {
@XmlAttribute("sample-field")
private String _myField;
}
XML document for the Bean
<Bean sample-field="A sample value"> </Bean> @XmlAttribute definition
@Target(value={FIELD,METHOD})
public @interface XmlAttribute {
public String name() default "##default";
public boolean required() default false;
public String namespace() default "##default";
}
@XmlElement@XmlElement marks a field or property as serialized to an XML element. It can also customize the XML element name and namespace. @XmlElement can work with @XmlAccessorType to select which fields and properties should be serialized to XML. By default, public fields and properties will be serialized. Adding @XmlElement to a private field will mark that field as serializable. @XmlElement can also customize the XML element name. By default, the XML element name is taken from the field name or the property name. The @XmlElement for a private field
@XmlRootElement
class Bean {
@XmlElement("sample-field")
private String _myField;
}
XML document for the Bean
<Bean> <sample-field>A sample value</sample-field> </Bean> @XmlElement definition
@Target(value={FIELD,METHOD})
public @interface XmlElement {
public String name() default "##default";
public boolean nillable() default false;
public boolean required() default false;
public String namespace() default "##default";
public String defaultValue() default "\u0000";
public Class type() DEFAULT.class;
}
@XmlElements@XmlElements allows lists to contain multiple different tags. It contains a list of @XmlElement values allowed as values. @XmlElement allowing two tags
class Bean {
@XmlElements({
@XmlElement(name="a",type=BeanA.class),
@XmlElement(name="b",type=BeanB.class)
})
private List<SubBean> data = new List<SubBean>();
}
class BeanA extends SubBean {
@XmlValue
private String data;
}
class BeanB extends SubBean {
@XmlValue
private String data;
}
XML document for the example
<Bean> <a>Some BeanA Data</a> <b>Some BeanB Data</b> <a>Another BeanA Data</a> </Bean> @XmlElements definition
@Target(value={FIELD,METHOD})
public @interface XmlElements {
public XmlElement[] value();
}
@XmlElementWrapper@XmlElementWrapper adds a wrapper XML tag for list values. By default, JAXB list values are serialized directly without any extra tags. @XmlElementWrapper adds a container XML tags. Bean example with @XmlElementWrapper
class Bean {
@XmlElementWrapper(name="values")
private List<String> data = new ArrayList<String>();
}
XML document for example
<Bean>
<values>
<data>Some data</data>
<data>Another item</data>
<data>Third item</data>
</values>
</Bean>
@XmlElementWrapper definition
@Target(value={FIELD,METHOD})
public @interface XmlElementWrapper {
public String name() default "##default";
public String namespace() default "##default";
public boolean nillable() default false;
}
@XmlJavaTypeAdapter@XmlJavaTypeAdapter specifies a Java class which converts helper values to final values. In some cases, the Java model may not directly match the XML model. For example, it's complicated to represent Java maps in XML. The @XmlJavaTypeAdapter provides a standard way of managing complex types. Maps in a Bean
class Bean {
@XmlJavaTypeAdapter(MyMapAdapter.class)
private HashMap<String,String> map;
}
class MyMapAdapter
extends XmlAdapter<Temp,Map<String,String>> {
...
}
class Temp {
@XmlElement
private List<Item> entry = new ArrayList<item>();
}
class Item {
@XmlAttribute
private String key;
@XmlAttribute
private String value;
}
XML Document
<Bean> <entry key="a" value="data-a"/> <entry key="b" value="data-b"/> <entry key="c" value="data-c"/> </Bean> @XmlJavaTypeAdapter
@Target({PACKAGE, FIELD, METHOD, TYPE, PARAMETER})
public @interface XmlJavaTypeAdapter {
Class<? extends XmlAdapter> value();
Class type() default DEFAULT.class;
}
@XmlRootElement@XmlRootElement marks a class as a top-level XML node. @XmlRootElement can also be used with @XmlElementRef to handle some inheritance situations. The @XmlRootElement for renaming
@XmlRootElement(name="my-bean")
class Bean {
public String data;
}
XML document for the Bean
<my-bean> <data>A sample value</data> </my-bean> @XmlRootElement definition
@Target(value=TYPE)
public @interface XmlRootElement {
public String name() default "##default";
public String namespace() default "##default";
}
@XmlTransient@XmlTransient marks a field or property as unserializable. JAXB will ignore the transient field. @XmlTransient annotation
@Target(value={FIELD,METHOD})
public @interface XmlTransient {
}
@XmlValue@XmlValue marks a single field as representing the entire content of the bean. If a bean has an @XmlValue annotation, no other property or field may be serialized. @XmlValue filling a bean
class Bean {
@XmlValue
private String data;
}
XML document for @XmlValue
<Bean>Sample Data</Bean> @XmlValue definition
@Target(value={FIELD,METHOD})
public @interface XmlValue {
}
|
1. JAVA -> XML (JAXB)
2. JAXB -> JSON (Jersey)
3. JAVA -> XML (XStream)
4. JAVA -> JSON (XStream)
1. 맛보기
{
"userid": "alseom",
"username": "알썸",
"email": "alseom@alseom.co.kr",
"regdate": "2009-11-26 17:58:00.671 KST"
}
참고
http://blog.openframework.or.kr/51
http://vicki.tistory.com/36
http://xstream.codehaus.org/json-tutorial.html
http://gyumee.egloos.com/1296932
http://bluesky.springnote.com/pages/375546
http://www.ksug.org/91
1. JAVA -> XML (JAXB)
2. JAXB -> JSON (Jersey)
3. JAVA -> XML (XStream)
4. JAVA -> JSON (XStream)
1. 맛보기
2. Annotations 이용
기타 나머지 Anotations 은 [여기] 를 참고하자.. 아~ 구찮어. ㅋ
JAXB의 Anotations 개념과 비슷해서 이해하기 어렵지 않다.
1. JAVA -> XML (JAXB)
2. JAXB -> JSON (Jersey)
3. JAVA -> XML (XStream)
4. JAVA -> JSON (XStream)
삽질중...
http://blog.openframework.or.kr/archive/200903
http://jackson.codehaus.org/Tutorial
http://blogs.sun.com/japod/entry/json_entity_providers_in_jersey
https://jira.jboss.org/jira/browse/RESTEASY-320
http://blogs.sun.com/japod/entry/better_json_available_in_jersey
http://old.nabble.com/Rendering-Collection<T>-objects-to-JSON-td22920874.html
http://vicki.tistory.com/36
http://mudchobo.tomeii.com/tt/275
http://blog.kangwoo.kr/3
http://ohgyun.com/43
http://blog.openframework.or.kr/67
http://openframework.or.kr/Wiki.jsp?page=Jeysey_start1
http://xstream.codehaus.org/json-tutorial.html
http://www.caucho.com/resin/doc/jaxb-annotations.xtp#@XmlElementWrapper
http://forums.java.net/jive/message.jspa?messageID=264033 (New Window)
http://www.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/5.0.0/html/RESTEasy/JAXB_and_JSON_provider.html
http://vicki.tistory.com/299
http://stackoverflow.com/questions/818327/jaxb-how-should-i-marshal-complex-nested-data-structures
xml <-> java object ... 삽질할 생각을 하니 답이 안 나온다.
그나마 Digester, apache의 xml Project가 있긴하지만, 성에 차지 않는다.
그래서 여기저기 찾아본 결과 JAXB, XStream 이 급 땡기게 한다. ㅎ
아주 기본적인 수준의 사용법만 정리해 본다.
1. JAVA -> XML (JAXB)
2. JAXB -> JSON (Jersey)
3. JAVA -> XML (XStream)
4. JAVA -> JSON (XStream)
0. JAXB란?
JAXB는 XML 사용 시 낮은 수준의 정보에서 사용자와 사용자의 코드를 숨겨 자바 애플리케이션의 XML 데이터를 간단히 사용할 수 있도록 합니다. JAXB를 사용하면 XML과 자바 간에 쉽게 앞뒤로 이동할 수 있습니다. JAXB 구현은 XML 스키마를 받아 해당 스키마에 매핑되는 자바 클래스를 생성하는 스키마 컴파일러를 제공합니다. XML 문서의 데이터는 JAXB의 바인딩 런타임 프레임워크를 통해, 스키마 컴파일러가 생성한 클래스에 자동으로 바인딩될 수 있습니다. 이 작업을 언마샬링(Unmarshalling)이라고 합니다. 언마샬링되면 필요에 따라 콘텐츠를 Java로 조작하거나 수정할 수 있습니다. JAXB는 자바 개체에서 XML 인스턴스 문서로 데이터를 쓸(마샬링할) 수도 있습니다. JAXB는 경우에 따라 이러한 작업의 일부로 콘텐츠에 대한 검증을 수행합니다. (SDN 발췌)
1. 맛보기
따로 설명이 필요 없을정도로 심플하다.
2. List
List는 기본적으로 지원을 해 준다.
확인해봐 줄 점은.. @XmlElementWrapper 정도.. List 에 대해서 한번더 묶어 준다.
아쉬운점은 <items size="2"> 와 같이 size값을 속성으로 넣어주고 싶었지만, 기본옵션으로는 힘들것 같다. 한번더 쌓줘야 할것 같다. --;
2. Map
문제는 Map 형태의 데이터이다.
List처럼 기본적으로 지원이 되지 않기 때문에 Adapter를 별도로 구현해야 한다.
Map을 기본 지원 형식으로 변환을 해야 하는데, 본인이 원하는 형대로 구성을 하면 된다.
Map형태를 List형태로 변환을 해서 뿌려질수 있도록 Adapter를 구현해 보겠다.
Adapter는 javax.xml.bind.annotation.adapters.XmlAdapter를 상속받아 marshal(), unmarshal() 를 Overriding 해야 한다.
XmlAdapter<ListFormatType, Map<String, Item>> 에서 앞에 ListFormatType는 변환후의 처리될 Object 이고, 뒤에 Map<String, Item>은 변환대상 포멧이다.
결과적으로 Adapter를 통해서 ListFormatType이 xml로 변환된다.
3. 참고
삽질하는 동안 여기저기서 참고했던 사이트 들 입니다.
http://blog.sdnkorea.com/blog/tag/jaxb (New Window)
http://vicki.tistory.com/tag/JAXB (New Window)
기타 많~~은 사이트..
댓글을 달아 주세요