使用Eclipselink Moxy,您可以添加属性来操纵输出。
public class Main {
public static void main(String[] args) {
Book book = new Book();
book.title = "hello";
JAXBContext context;
try {
context = JAXBContextFactory.createContext(new Class[] {Book.class}, null);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(book, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
将导致:{“ book”:{“ title”:“ hello”}}
org.eclipse.persistence.moxy-2.5.1.jar and org.eclipse.persistence.core-core-2.5.1.jar在classPath上需要jar。当我自己玩这个时,我遇到了: 最热门的JAXB答案. 。尤其是Blaise Doughan回答非常有帮助的地方。搜索
MarshallerProperties.MEDIA_TYPE, "application/json"
有关他的更多例子。