我正在寻找一个 Java 库来将我的域对象转换为扁平化的 JSON
例如。
public class Person {
String name
Address homeAddress
}
public class Address {
String street
String zip
}
JSON: {name:'John', homeAddress_street: '123 Street', homeAddress_zip: 'xxxxx'}
我研究了 XStream、Eclipse MOXy、FlexJSON、JSON-lib 和 gson
我的目标是摆脱我的 json 包装器类并最小化代码。我想要一个通用服务,它可以采用我拥有的任何域模型类并获得 json 表示,而无需为每种类型的模型编写 xml 描述符或任何自定义转换器。 1 级深的深度对我的模型来说已经足够了。我没有在上述库中找到使用注释或内置功能的简单通用解决方案,但我可能忽略了它们。有没有可以做到这一点的非侵入式图书馆?或者也许是我列出的?我正在使用 Hibernate,所以该库必须能够处理 CGLib 代理
最佳答案
注意:我是 EclipseLink JAXB (MOXy) JAXB (JSR-222) 的领导和成员专家组。
下面是一个示例,说明如何通过利用 @XmlPath
扩展来使用 MOXy 完成此操作。
人
package forum7652387;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlAccessorType(XmlAccessType.FIELD)
public class Person {
String name;
@XmlPath(".")
Address homeAddress;
}
地址
package forum7652387;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Address {
@XmlElement(name="homeAddress_street")
String street;
@XmlElement(name="homeAddress_zip")
String zip;
}
jaxb.properties
要将 MOXy 指定为您的 JAXB 提供者,您需要在与您的域类相同的包中添加一个名为 jaxb.properties
的文件,其中包含以下条目:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示
package forum7652387;
import java.io.StringReader;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setProperty("eclipselink.media-type", "application/json");
unmarshaller.setProperty("eclipselink.json.include-root", false);
String jsonString = "{\"name\":\"John\", \"homeAddress_street\":\"123 Street\", \"homeAddress_zip\":\"xxxxx\"}";
StreamSource jsonSource = new StreamSource(new StringReader(jsonString));
Person person = unmarshaller.unmarshal(jsonSource, Person.class).getValue();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty("eclipselink.media-type", "application/json");
marshaller.setProperty("eclipselink.json.include-root", false);
marshaller.marshal(person, System.out);
}
}
输出
{"name" : "John", "homeAddress_street" : "123 Street", "homeAddress_zip" : "xxxxx"}
了解更多信息
关于Java JSON 对象扁平化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7652387/