我有以下java类
methods: {
factorial(x) {
if (!x) {
x = this.value;
}
return x * this.factorial(x-1);
},
},
我为每个列表都有实体类,例如MappingMetadata,TabularColumnGroup,TabularStates。 我想为此pojo类获取json数据。我该怎么办。
什么是
public class TabularDescriptor extends ReportDescriptor {
private String generatorClass;
private String targetClass;
private String name;
private String sublabel;
private String reportName;
private List<MappingMetadata> mappings = null;
private List<TabularColumnGroup> columnGroups = null;
private List<TabularStates> states = null;
:
:
and its getters and settere
无论如何,如果可以的话,我可以在浏览器上显示json内容吗?谢谢。
答案 0 :(得分:3)
您可以使用 ObjectMapper 或 Gson 将Class转换为JSON,反之亦然。
(我建议使用ObjectMapper)
- 对象映射器
Intro to the Jackson ObjectMapper
- GSON
How to convert Java object to / from JSON
- 比较
答案 1 :(得分:3)
有2个使用Java处理JSON序列化/反序列化的库:
GSON-Google的Java序列化/反序列化(docs)库。
等级:
dependencies { implementation 'com.google.code.gson:gson:2.8.6'}
Maven:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
TabularDescriptor tabularDescriptor = new TabularDescriptor();
Gson gson = new Gson();
String json = gson.toJson(obj);
Jackson-用于Java序列化/反序列化(docs)的另一个库,完全嵌入了所有spring-boot-starter-web
依赖项,<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
是{{3的依赖项之一}}-流行的Java IOC / DI框架。
Maven:
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.0.1'
等级:
TabularDescriptor tabularDescriptor = new TabularDescriptor();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(tabularDescriptor);
序列化代码段:
<dependency>
<groupId>com.sun.xml.messaging.saaj</groupId>
<artifactId>saaj-impl</artifactId>
<version>1.5.0</version>
</dependency>
详细信息:必须具有所有公共获取者/设置者,才能对对象进行完整的序列化和反序列化(以其最简单的形式)。在任何情况下,都必须有一个空的构造函数。
参考文章:
答案 2 :(得分:1)
我建议您将Jackson添加到您的项目中,这很容易使用。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
在Java代码中可以这样使用:
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(tabularDescriptor);
TabularDescriptor newTabularDescriptor = objectMapper.readValue(json, TabularDescriptor.class);