为密钥始终不同的json文件创建Java对象

时间:2018-10-31 11:04:51

标签: java json class object gson

.json文件看起来像这样

XYZ.json

{
"Business Information": {
    "xpath": "//span[text()='Business Information']",
    "elementType": "LINK",
    "findBy": "XPath"
},
"AP and Ship-To Information": {
    "xpath": "//span[text()='AP and Ship-To Information']",
    "elementType": "LINK",
    "findBy": "XPath"
},
"Other Business Details": {
    "xpath": "//span[text()='Other Business Details']",
    "elementType": "LINK",
    "findBy": "XPath"
},
"Bank and Trade Information": {
    "xpath": "//span[text()='Bank and Trade Information']",
    "elementType": "LINK",
    "findBy": "XPath"
}
}

我想创建一个可以存储这些密钥的Java对象。但是问题是有100多个不同的密钥。为嵌套元素创建对象很容易。

Tabs.class

public class Tabs {
    private String xpath;
    private String elementType;
    private String findBy;
}

但是对于类TabNames ...

TabNames.class

public class TabNames {
    Tab Business Name; // Cannot create Object with whitespace
    Tab 2;
    Tab 3;
    and so on.. // there maybe 100s of tabs from JSON

配置这样的对象将是不可能的,并且仅仅是愚蠢的。谁能提供替代或更好的解决方案?

2 个答案:

答案 0 :(得分:1)

为此,您可以使用HashMap

HashMap<String, Tabs> myTabs = new HashMap<>();
myTabs.put("Business Information", new Tabs());

在这里,您可以将new Tabs()替换为已解析的Tabs类,然后将"Business Information"更改为与Tabs类关联的键。通过遍历JSON对象,可以在for循环中完成此操作。

之后,您可以根据Tabs的{​​{1}}值获取Key对象:

HashMap

答案 1 :(得分:0)

代替类似的结构

{
"Business Information": {
    "xpath": "//span[text()='Business Information']",
    "elementType": "LINK",
    "findBy": "XPath"
},

我建议这样做:

[
    {
        "type": "tab",
        "name": "Business Information",
        "xpath": "//span[text()='Business Information']",
        "elementType": "LINK",
        "findBy": "XPath"
    }, {
        "type": "tab",
        "name": "Business Information",
        "xpath": "//span[text()='Business Information']",
        "elementType": "LINK",
        "findBy": "XPath"
    }, ...

]

现在,您可以轻松地遍历JSON数组,并且每个成员都是“ tabs.class”类的对象。属性没有任何空间,因此可以直接使用。