互转工具类
import lombok.extern.slf4j.Slf4j;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
/**
* Xml与对象转换工具类
*
* @author
* @date 2022/10/24
*/
@Slf4j
public class XmlUtil {
public static String toXml(Object obj) {
String xmlStr = null;
JAXBContext jaxbContext = null;
Marshaller marshaller = null;
StringWriter writer = null;
try {
jaxbContext = JAXBContext.newInstance(obj.getClass());
marshaller = jaxbContext.createMarshaller();
writer = new StringWriter();
marshaller.marshal(obj, writer);
xmlStr = writer.toString();
} catch (JAXBException e) {
log.error("xml转对象失败");
}
return xmlStr;
}
public static <T> T fromXml(String xmlStr, Class<T> aClass) {
T result = null;
JAXBContext jaxbContext = null;
try {
StringReader reader = new StringReader(xmlStr);
jaxbContext = JAXBContext.newInstance(aClass);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
result = (T) jaxbUnmarshaller.unmarshal(reader);
} catch (JAXBException e) {
e.printStackTrace();
}
return result;
}
}
类需要的注解 @XmlRootElement() @XmlAttribute() @XmlElement()
import lombok.Data;
import javax.xml.bind.annotation.*;
/**
*
*
* @author
* @date 2022/10/21
*/
@Data
@XmlRootElement(name = "VariCfgSec")
@XmlAccessorType(value = XmlAccessType.FIELD)
public class WebApiConfigReq {
/**
* action: DEVICE_QUERY查询设备版本相关信息
*/
@XmlAttribute(name = "Action")
private String action;
private StSnap stSnap;
private StOSD stOSD;
@XmlElement(name = "stVersion")
private String stVersion;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
@Data
public static class StOSD {
@XmlAttribute(name = "ucFD_TempEnable")
private String ucFD_TempEnable;
@XmlAttribute(name = "ucFD_GPSEnable")
private String ucFD_GPSEnable;
@XmlAttribute(name = "ucFD_DeviceNoEnable")
private String ucFD_DeviceNoEnable;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
@Data
public static class StSnap {
@XmlAttribute(name = "ucFD_MultiSnapEnable")
private String ucMultiSnapEnable;
@XmlAttribute(name = "uiFD_Interval")
private String uiInterval;
@XmlAttribute(name = "ucFD_SnapSubResolution")
private String ucSnapSubResolution;
@XmlAttribute(name = "ucFD_PrePSnapEn")
private String ucPrePointSnapEn;
@XmlAttribute(name = "ucFD_PrePSnapChn")
private String ucPrePointSnapChn;
@XmlAttribute(name = "strFD_PrePName")
private String strPrePointName;
@XmlAttribute(name = "strFD_PrePWSec")
private String strPrePointWaitSec;
}
}