我有一个 JSON 文件,我正在尝试XML
使用JAXB
注释方法将其转换为。现在一切正常,我可以将其转换JSON
为XML
. 现在我正在尝试稍微重构代码,以便我的类看起来干净。因此,我试图删除我的方法class
并使其JAXB XMLAdapter
可以被其他类重用。
基本上我想将XMLSupport
方法从CarInfo
类移动到XMLAdapter
. 当我CarInfo
将对象移动到XMLAdapter
.
以下是我的JSON
文件(为简单起见已对其进行了修改):
{
"brand": "Ferari",
"build": "Italy",
"engine": "Mercedes",
"year": "2021"
}
以下是XML
我希望JAXB
提供的:(观察carInfo
不存在JSON
但我需要XML
匹配标准的标签XSD
)
<?xml version="1.0"?>
<Car>
<brand>Ferari</brand>
<build>Italy</build>
<carinfo>
<engine>Mercedes</engine>
<year>2021</year>
</carinfo>
</Car>
以下是我拥有的类:(Car
与 JSON 元素匹配的类)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlTransient
@XmlSeeAlso({MyCar.class});
public class Car{
private String brand;
private String build;
@XmlTransient
private String engine;
@XmlTransient
private String year;
//Getter, Setters and other consturctiores ommited
}
以下是通过添加标签MYCar
构建的类:XML
carInfo
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Car")
@XmlType(name = "Car", propOrder = {"brand","build", "carInfo"})
public class MyCar extends Car{
@XmlElement(name="carInfo")
private CarInfo carInfo;
public MyCar xmlSupport() {
if(carInfo == null){
carInfo = new Carinfo();
}
carInfo.setEngine(getEngine);
carInfo.setYear(getYear());
return this;
}
}
以下是我的CarInfo
类,它充当additional
围绕类构建标签的助手MyCar
:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {"engine","year"})
public class Carinfo{
private String engine;
private String year;
//Getter, Setters and other consturctiores ommited
}
以下是我的Main
课程,它实际上是XML
通过使用JAXBCOntext
public class Main{
public static void main(String[] args){
JAXBContext context = JAXBContext.newInstance(MyCar.class);
Marshaller mar = context.createMarshaller();
mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
mar.marshal((MyCar).xmlSupport(), System.out);
System.out.println("-----------------");
}
}
现在回到我的主要问题:正如我们从MyCar
类中看到的那样,我有一个XMLSupport
实际填充CarInfo
对象的方法,然后使用该方法创建XML
. 有没有办法可以把它移到XMLAdapter
?
我尝试创建XMLAdapter
但我不确定如何 CarInfo
从适配器填充对象:
public class MyCar extends Car{
@XmlElement(name="carInfo")
@XmlJavaTypeAdapter(ExtensionAdapter.class)
@XmlElement(name = "carInfo")
private CarInfo carInfo;
}
以下是我Adapter
尝试过的课程: public class ExtensionAdapter extends XmlAdapter<CarInfo, CarInfo> {
@Override
public CarInfo unmarshal(CarInfo valueType) throws Exception {
System.out.println("UN-MARSHALLING");
return null;
}
@Override
public CarInfo marshal(CarInfo boundType) throws Exception {
System.out.println("MARSHALLING");
System.out.println(boundType);
//I get boundType as NULL so I am not sure how to convert the xmlSupport Method to Adapter so I can use this adapter with multiple class
return null;
}
}