繁体   English   中英

将 XML 解组到 POJO

[英]Unmarshalling XML to POJO

我正在尝试将 xml 文件解组为 java object。 这是 xml 文件。 我不确定我们是否可以像下面的 xml 那样解组文件。 因为它有多种账户类型并且有几次相同的标签。 这会是解组的问题吗?

<?xml version="1.0" encoding="UTF-8"?>
<AccountTypes>
 <AccountType>
   <AccountTypeId>1</AccountTypeId>
   <AccountTypeDescription>savings</AccountTypeDescription>
 </AccountType>
<AccountType>
   <AccountTypeId>2</AccountTypeId>
   <AccountTypeDescription>checking</AccountTypeDescription>
 </AccountType>
<AccountType>
   <AccountTypeId>3</AccountTypeId>
   <AccountTypeDescription>401k</AccountTypeDescription>
 </AccountType>
</AccountTypes>

我的代码是这样的:XmlToJava.java

 public static void main(Strings[] args){

  try {
    File file = new File("pathname");
    JAXBContext context = JAXBContext.newInstance(Account.class);
      Unmarshaller unmarshaller = context.createUnmarshaller();
      Account account = (Account) unmarshaller.unmarshal(file);
  } catch(Exception e){
     e.printStackTrace(); 
 }
}

我的 POJO 看起来像这样:我有正确的注释吗?

@XmlRootElement(name="AccountTypes")
@XmlAccessorType(XmlAccessType.FIELD)
public class Account implements Serializable{

   @XmlElement(required= true)
   private Integer accountTypeId;

   @XmlElement(required=true)
   private String description;

   //has all getters, setters, contructors, toString() menthod

}

我可以看到您在 XML 文件中有多个帐户,因此您实际上应该解组Collection<Account> 或者你也可以有一个包装器 class 我相信:

@XmlRootElement(name="AccountTypes")
@XmlAccessorType(XmlAccessType.FIELD)
public final class AccountTypes implements Serializable {
    @XmlElement(name="AccountType")
    private List<Account> accounts = /* whatever structure you prefer */;
}

我也宁愿有这样的 POJO:

@XmlRootElement(name="AccountType")
@XmlAccessorType(XmlAccessType.FIELD)
public class Account implements Serializable {

   @XmlElement(required=true, name="AccountTypeId")
   private Integer id;

   @XmlElement(required=true, name="AccountTypeDescription")
   private String description;
}

使用account.getId()而不是大account.getAccountTypeId()才有意义。

请注意, Accountname=AccountType并且AccountTypesname=AccountTypes并且我还修复了name="AccountTypeDescription"

试试这个方法:

POJO:

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "accountType" })
@XmlRootElement(name = "AccountTypes")
public class AccountTypes {

    @XmlElement(name = "AccountType", required = true)
    protected List<AccountTypes.AccountType> accountType;

    public List<AccountTypes.AccountType> getAccountType() {
        if (accountType == null) {
            accountType = new ArrayList<>();
        }
        return this.accountType;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = { "accountTypeId", "accountTypeDescription" })
    public static class AccountType {

        @XmlElement(name = "AccountTypeId")
        @XmlSchemaType(name = "unsignedByte")
        protected short accountTypeId;
        @XmlElement(name = "AccountTypeDescription", required = true)
        protected String accountTypeDescription;

        public short getAccountTypeId() {
            return accountTypeId;
        }

        public void setAccountTypeId(short value) {
            this.accountTypeId = value;
        }

        public String getAccountTypeDescription() {
            return accountTypeDescription;
        }

        public void setAccountTypeDescription(String value) {
            this.accountTypeDescription = value;
        }

    }

}

测试:


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Demo1 {

    public static void main(String[] args) throws JsonProcessingException, FileNotFoundException {
        
        ObjectMapper mapper = new ObjectMapper();
        
        FileInputStream file = new FileInputStream ("pathname");
        
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
                + "<AccountTypes>\r\n"
                + " <AccountType>\r\n"
                + "   <AccountTypeId>1</AccountTypeId>\r\n"
                + "   <AccountTypeDescription>savings</AccountTypeDescription>\r\n"
                + " </AccountType>\r\n"
                + "<AccountType>\r\n"
                + "   <AccountTypeId>2</AccountTypeId>\r\n"
                + "   <AccountTypeDescription>checking</AccountTypeDescription>\r\n"
                + " </AccountType>\r\n"
                + "<AccountType>\r\n"
                + "   <AccountTypeId>3</AccountTypeId>\r\n"
                + "   <AccountTypeDescription>401k</AccountTypeDescription>\r\n"
                + " </AccountType>\r\n"
                + "</AccountTypes>";

        AccountTypes AccountTypes  = convertXMLToObject(AccountTypes.class, xml);
        System.out.println("mapper from string "+ mapper.writeValueAsString(AccountTypes));
        
        AccountTypes AccountTypes1  = convertXMLToObject(AccountTypes.class, file);
        System.out.println("mapper from file "+ mapper.writeValueAsString(AccountTypes1));
    }
    
    @SuppressWarnings("unchecked")
    public static <T> T convertXMLToObject(Class<T> clazz, String xml) {
        try {

            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller um = context.createUnmarshaller();
            return (T) um.unmarshal(new StringReader(xml));
        } catch (JAXBException je) {
            throw new RuntimeException(String.format("Exception while Unmarshaller: %s", je.getMessage()));
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T convertXMLToObject(Class<T> clazz, InputStream file) {

        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            T obj = (T) jaxbUnmarshaller.unmarshal(file);
            return obj;

        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RuntimeException(String.format("Exception while Unmarshaller: %s", e.getMessage()));
        }
    }

}

结果如下:

mapper from string {"accountType":[{"accountTypeId":1,"accountTypeDescription":"savings"},{"accountTypeId":2,"accountTypeDescription":"checking"},{"accountTypeId":3,"accountTypeDescription":"401k"}]}

mapper from file {"accountType":[{"accountTypeId":1,"accountTypeDescription":"savings"},{"accountTypeId":2,"accountTypeDescription":"checking"},{"accountTypeId":3,"accountTypeDescription":"401k"}]}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM