我有以下Java类:
public class ModuleParsed {
String id_component;
String id_instance;
Map<ModuleParam, ModuleParam> input;
Map<ModuleParam, List<ModuleParam>> output;
int id_paas;
}
和
public class ModuleParam {
String name;
Object type;
}
JSON应该将其解析为List<ModuleParsed>
?
listModules = gson.fromJson(br, new TypeToken<List<ModuleParsed>>() {}.getType());
在我介绍输入和输出参数之前,一切都很好。
修改
通过执行相反的过程,我发现JSON应该类似于
[
{
"id_component": "mod1",
"id_instance": "mod1_inst1",
"input": {
"moduleParam": {
"name": "param3",
"type": "obj3"
},
"moduleParam": {
"name": "param2",
"type": "obj2"
}
},
"id_paas": 1
},
{
"id_component": "mod2",
"id_instance": "mod2_inst1",
"input": {
"moduleParam": {
"name": "param3",
"type": "obj3"
},
"moduleParam": {
"name": "param2",
"type": "obj2"
}
},
"id_paas": 1
}
]
其中moduleParam元素类似于:parser.ModuleParam@36c51089
无论我如何命名这些元素,我都会收到以下错误:
Exception in thread "main" com.google.gson.JsonParseException: Expecting object found: "moduleParam"
如何使用Gson获取课程ModuleParsed
?
答案 0 :(得分:0)
按照@Brian的评论,我意识到我不需要使用复杂的对象作为键,所以这是我的解决方案。
public class ModuleParsed {
String id_component;
String id_instance;
Map<String, ModuleParam> input;
Map<String, List<ModuleParam>> output;
int id_paas;
}
public class ModuleParam {
String name;
String id_module;
String id_instance;
}
我为其构建了以下JSON
[
{
"id_component": "mod1",
"id_instance": "mod1_inst1",
"input": {
"input1": {}
},
"output": {
"output1": [
{
"name": "input1",
"id_module": "mod2",
"id_instance": "mod2_inst1",
"type": "paramType"
},
{
"name": "input2",
"id_module": "mod2",
"id_instance": "mod2_inst1",
"type": "paramType"
}
],
"output2": []
},
"id_paas": 1
},
{
"id_component": "mod2",
"id_instance": "mod2_inst1",
"input": {
"input1": {
"name": "output1",
"id_module": "mod1",
"id_instance": "mod1_inst1",
"type": "paramType"
},
"input2": {
"name": "output1",
"id_module": "mod1",
"id_instance": "mod1_inst1",
"type": "paramType"
}
},
"output": {},
"id_paas": 1
}
]
这次正确解析了JSON。