0

我有以下 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"

我怎样才能获得ModuleParsedGson 的课程?

4

1 回答 1

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 被正确解析了。

于 2013-03-07T13:49:30.330 回答