我正在寻找一个 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'}
Run Code Online (Sandbox Code Playgroud)
我研究过 XStream、Eclipse MOXy、FlexJSON、JSON-lib 和 gson
我的目标是摆脱 json 包装类并最小化代码。我想要一个通用服务,它可以接受我拥有的任何域模型类并获得 json 表示,而无需为每种类型的模型编写 xml 描述符或任何自定义转换器。对于我的模型来说,1 级深度就足够了。我还没有找到使用注释或上述库中内置功能的简单通用解决方案,但我可能忽略了它们。有没有一个非侵入式的库可以做到这一点?或者也许是我列出的一个?我正在使用 Hibernate,因此库必须能够处理 CGLib 代理
注意: 我是EclipseLink JAXB (MOXy) 的负责人,也是JAXB (JSR-222)专家组的成员。
下面是如何利用 MOXy 扩展来完成此操作的示例@XmlPath。
人
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;
}
Run Code Online (Sandbox Code Playgroud)
地址
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;
}
Run Code Online (Sandbox Code Playgroud)
jaxb.属性
要将 MOXy 指定为 JAXB 提供程序,您需要添加一个jaxb.properties在与域类相同的包中调用的文件,其中包含以下条目:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Run Code Online (Sandbox Code Playgroud)
演示
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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出
{"name" : "John", "homeAddress_street" : "123 Street", "homeAddress_zip" : "xxxxx"}
Run Code Online (Sandbox Code Playgroud)
了解更多信息
| 归档时间: |
|
| 查看次数: |
4320 次 |
| 最近记录: |