JAVA XML轉對象


最近遇到XML轉對象進行業務操作的問題

這是我需要解析的XML

 

 

 

1,建XML對應自己需要參數的Bean。有的很長很亂,沒必要全部建,只建自己需要的就行了

import lombok.Data;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;

@Data
@XmlRootElement(name = "EventNotificationAlert")//這個是上面圖片開頭和結尾那個標簽名稱,你需要替換成你自己的
@XmlAccessorType(XmlAccessType.FIELD)
public class EventNotificationAlert {
    private String ipAddress;
    private String portNo;
    private String protocol;
    private String macAddress;//MAC
    private String dynChannelID;//2不知道什么
    private String channelID;
    private Date dateTime;
    private String activePostCount;
    private String eventType;
    private String eventState;
    private String eventDescription;
    private String deviceID;
    private String thermalURL;
}

2,寫解析代碼

import com.zhcz.wisdom.yw.eneity.EventNotificationAlert;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;

public class ToWyServer {
    @Autowired
    private RestTemplate restTemplate;

    public static boolean FireAlarm(String date){
        if (StringUtils.isEmpty(date)) return false;
        System.out.println(date);
        Object map = ToWyServer.convertXmlStrToObject(EventNotificationAlert.class,date);
        EventNotificationAlert eee = (EventNotificationAlert) map;
        System.err.println(eee.toString());
        return true;
    }

    /**0
     * 將String類型的xml轉換成對象
     */
    public static Object convertXmlStrToObject(Class<?> clazz, String xmlStr) {
        Object xmlObject = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            // 進行將Xml轉成對象的核心接口
            Unmarshaller unmarshal = context.createUnmarshaller();
            StringReader sr = new StringReader(xmlStr);
            xmlObject = unmarshal.unmarshal(sr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return xmlObject;
    }

  

完成!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM