如果值得更改并且您愿意,我建议您查看Jackson (https://github.com/FasterXML/jackson)。它可以开箱即用,只需很少或没有注释或自定义。
“Jackson 是用于处理 JSON 的几个可用库之一。其他一些是用于 JSON 处理的 Boon、GSON 和 Java API。
Jackson 相对于其他库的一个优势是它的成熟度。 Jackson 已经发展到足以成为一些主要 Web 服务框架的首选 JSON 处理库 (...)"
DZone的这篇好文章可能会给你一些亮点:https://dzone.com/articles/processing-json-with-jackson
尽管如此,由于您没有定义“优雅”对您意味着什么,并且正如您所说的 GSON 我同意这个答案可能不适合您(并且可能会消失;))。
我阅读了关于这个主题的所有答案,但没有找到任何可以解决我的问题的东西
是的,如果您需要更多信息,您还需要向我们提供您的实际 issue 的详细信息。
编辑:添加了 Jackson 的示例代码。
以下是 Jackson 的优雅外观(当然,通过工厂、构建器、帮助器使用预配置的映射器,它甚至可以更好......)。
public class Workspace {
final ObjectMapper objMapper = new ObjectMapper();
List<Product> products;
public Workspace() {
}
public Workspace(List<Product> products) {
this.products = products;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public String serialize() throws IOException {
try {
return objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static Workspace deserialize(String json) throws IOException {
return new ObjectMapper().readValue(json, Workspace.class);
}
}
public class Product {
List<Module> modules;
public Product() {
}
public Product(List<Module> modules) {
this.modules = modules;
}
public List<Module> getModules() {
return modules;
}
public void setModules(List<Module> modules) {
this.modules = modules;
}
}
public class Module {
List<Parameter> parameters;
public Module() {
}
public Module(List<Parameter> parameters) {
this.parameters = parameters;
}
public List<Parameter> getParameters() {
return parameters;
}
public void setParameters(List<Parameter> parameters) {
this.parameters = parameters;
}
}
public class Parameter {
String name;
String type;
public Parameter() {
}
public Parameter(String name, String type) {
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public class WorkspaceTest {
/**
* Test of serialize method, of class Workspace.
*/
@Test
public void testSerDeserialize() throws Exception {
// Build sample:
Workspace instance = new Workspace(
Collections.singletonList(new Product(
Collections.singletonList(new Module(
Collections.singletonList(new Parameter("Hello","World")))))));
// SER
String serialized = instance.serialize();
assertNotNull(serialized);
System.out.println("Serialized JSON: \n"+serialized);
// DSER
Workspace deserialized = Workspace.deserialize(serialized);
// MATCH
assertEquals(serialized, deserialized.serialize());
System.out.println("Match!");
}
}
输出:
Serialized JSON:
{
"products" : [ {
"modules" : [ {
"parameters" : [ {
"name" : "Hello",
"type" : "World"
} ]
} ]
} ]
}
Match!