MOXy传统上是XML到Object的对象,但是它也可以通过MoxyJsonProvider生成JSON。 MOXy还具有通过XPath映射在1-1转换之外映射到XML的工具。您还可以使用此工具来修改JSON输出吗?我对此表示怀疑,但一位同行问我这个问题。
现在,我可以通过FasterXML Jackson通过一些技术来实现这一点,例如为我想要从另一个实体获得的特定属性创建@JsonProperty
或通过使用我要创建嵌套JSON对象的字段填充地图。
// XML Input
// I don't have this file. I'll try to generate it based on the code but the meat and bones of the question is in the transformation via
File xmlInput = new File(input.xml);
// Processs the XML
JAXBContext context = JAXBContext.newInstance("model");
Unmarshaller unmarshaller = context.createUnmarshaller();
CustomerImpl customerImpl =
(CustomerImpl) unmarshaller.unmarshal(xmlInput);
// Build the Customer Object
Customer customer = new Customer();
// Build the Address Object
ContactInfoImpl contactInfoImpl = customerImpl.getContactInfo();
if(null != contactInfoImpl) {
AddressImpl addressImpl = customerImpl.getAddress();
if(null != addressImpl) {
Address address = new Address();
customer.setAddress(address);
address.setStreet(addressImpl.getStreet());
}
}
Customer.java
@XmlRootElement
public class Customer {
@XmlPath("contact-info/address")
private Address address;
}
这将生成:
<customer>
<contact-info>
<address>
<street>123 Any Street</street>
</address>
</contact-info>
</customer>
这也可以用于生成修改后的JSON映射吗?即我可以使用它来将嵌套的JSON对象折叠到字段中或将字段包装到嵌套的JSON对象中吗?例子
{
"street" : "123 Any Street"
}
通过“ XMLPath”注释进行了修改:
Customer.java
@XmlRootElement
public class Customer {
@XmlPath("address")
private String address;
}
{
"address" : {
"street" : "123 Any Street"
}
}