Java 具有几个已知类的GSON
我有下面的jsonJava 具有几个已知类的GSON,java,json,gson,Java,Json,Gson,我有下面的json { "file": {"file": "foo.c", "owner": "user123"} "methods": [{"name": "proc1", "value":"val"}, {"name":"proc2","value":"val2"}] etc... } 我知道我可以做像这样的事情 class file{ public String file public String owner } class methods{
{ "file": {"file": "foo.c", "owner": "user123"}
"methods": [{"name": "proc1", "value":"val"}, {"name":"proc2","value":"val2"}]
etc...
}
我知道我可以做像这样的事情
class file{
public String file
public String owner
}
class methods{
public String name
public String value
}
我可以打电话
File file= gson.fromJson(jsonInString, File.class);
methods[] array = gson.fromJson(jsonInString, methods[].class);
但是,如果我需要处理一个包含许多对象的复杂json,我该怎么办呢
我不能指定
gson.fromJson(jsonInString,ListOfClasses)
我通常采用这种方法将任何复杂类从json转换为对象。这种方法几乎适用于列表、地图等所有东西。其思想很简单:为复杂类创建持有者,然后创建类。尽可能多地提供所需的深度。诀窍是匹配Json中的名称和持有者(以及子类)
文件配置:
class FileConfig{
public String file;
public String owner;
//define toString, getters and setters
}
方法类:
class Method{
public String name;
public String value;
//define toString, getters and setters
}
方法配置:
class MethodConfig{
List<Method> methods = null;
//define toString, getters and setters
}
构建配置:
public class HolderConfigBuilder {
public static HolderConfig build(JsonObject holderConfigJson) {
HolderConfig configHolderInstance = null;
Gson gsonInstance = null;
gsonInstance = new GsonBuilder().create();
configHolderInstance = gsonInstance.fromJson(holderConfigJson,HolderConfig.class);
return configHolderInstance;
}
}
演示类:
public class App
{
public static void main( String[] args )
{
HolderConfig configHolderInstance = null;
FileConfig file = null;
configHolderInstance = HolderConfigBuilder.build(<Input Json>);
file = configHolderInstance.getFile();
System.out.println("The fileConfig is : "+file.toString());
}
}
注意:编写代码以在测试代码中获取输入JSON
这样,无论何时向JSON添加更多元素,都必须为该元素创建一个单独的类,只需将JSON中的元素名称添加到HolderConfig中即可。您不需要更改代码的其余部分
希望有帮助。为什么在同一个json中有许多对象?它是为了优化网络带宽吗?不,它的思想是用户可以定义几个组件,例如,用户可以在与系统的一次交互中定义方法。在另一个例子中,用户去定义一个文件,所以这个json将分阶段构建,用户去选择文件,json将是文件:{data},方法:空,在用户去选择方法之后,它将拥有数据,想法是每个组件都是它自己的类,我将从类转到json,反之,如果你的json有一个预定义的模式,你可以声明一个大类(或者把它分成基类和子类),它包含你所期望的所有属性
public class App
{
public static void main( String[] args )
{
HolderConfig configHolderInstance = null;
FileConfig file = null;
configHolderInstance = HolderConfigBuilder.build(<Input Json>);
file = configHolderInstance.getFile();
System.out.println("The fileConfig is : "+file.toString());
}
}
{ "file": {"file": "foo.c", "owner": "user123"}
"methods": [
{"name": "proc1", "value":"val"},
{"name":"proc2","value":"val2"}
]
}