11
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

この時代にJackson formatter XMLでJavaBeanとXMLを変換してみた

Last updated at Posted at 2019-04-17

#経緯
お察しください

#準備
pomに下記を追加


<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.9.8</version>
</dependency>

#詳細な使い方
http://fasterxml.github.io/jackson-dataformat-xml/javadoc/2.9/

#もろもろのクラス準備
###前提
・Beanのデータを作るときにLombokの@Builderを使いました(本記事では触れてません)
  https://projectlombok.org/

###Bean

TestBean.java
@Data
@Builder
@JacksonXmlRootElement(localName = "top_element")
public class TestBean implements Serializable {

    // isAttribute = trueを付与すると属性になる
    @JacksonXmlProperty(localName = "id", isAttribute = true)
    private String topElement;

    @JacksonXmlProperty(localName = "test_field")
    private String testField;
    
    // ネストしたBeanも書ける
    @JacksonXmlProperty(localName = "test_inner_bean")
    private TestInnerBean testInnerBean;

    // Beanのリストをフィールドに持てる
    @JacksonXmlElementWrapper(localName = "dtls")
    @JacksonXmlProperty(localName = "dtl")
    private List<DtlsInnerDto> dtlsInnerDto;

###ネストするBean

TestInnerBean.java
@SuppressWarnings("serial")
@Data
@Builder
public class TestInnerBean implements Serializable {

    @JacksonXmlProperty(localName = "inner_field_one")
    private String innerFieldOne;

    @JacksonXmlProperty(localName = "inner_field_two")
    private String innerFieldTwo;
}

###ネストするBeanのリスト

DtlsInnerDto.java
@SuppressWarnings("serial")
@Data
@Builder
public class DtlsInnerDto implements Serializeble {
    @JacksonXmlProperty(localName = "dtl_item")
    private String dtlItem;
}

#Bean→XML変換処理のコード

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

String xml = new XmlMapper().writeValueAsString(Bean組み立て処理());

#変換結果

<top_element id="xxx">
  <test_field>xxx</test_field>
  <test_inner_bean>
     <inner_field_one>xxx</inner_field_one>
     <inner_field_two>xxx</inner_field_two>
  </test_inner_bean>
 <dtls>
    <dtl>xxx</dtl>
    <dtl>yyy</dtl>
    <dtl>zzz</dtl>
  </dtls>
</top_element>

#XML→Bean変換処理のコード

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

Beanクラス bean = new XmlMapper().readValue(xml文字列, Beanクラス.class)

##メモ

11
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?