为json文件创建一个Java对象,其中键总是不同的
.json文件如下所示 XYZ.json为json文件创建一个Java对象,其中键总是不同的,java,json,class,object,gson,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']",
{
"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个不同的密钥。为嵌套元素创建对象很容易
选项卡类
public class Tabs {
private String xpath;
private String elementType;
private String findBy;
}
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
但是对于类选项卡名
TabNames.class
public class Tabs {
private String xpath;
private String elementType;
private String findBy;
}
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
像这样配置一个对象是不可能的,而且是愚蠢的。有人能为这个问题提供一个替代或更好的解决方案吗?您可以为此使用
HashMap
,例如:
HashMap<String, Tabs> myTabs = new HashMap<>();
myTabs.put("Business Information", new Tabs());
而不是像这样的结构
{
"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”的对象。属性没有任何空间,因此可以直接使用。您是否可以修改JSON文件的布局/结构?这将是一个完美的解决方案,但是.json格式来自一个需要完全修改的私有框架。在以后将该对象写入类似的.json文件时,如何将密钥存储在对象中并保留格式?GSON将自动将
HashMap
对象解析为正确的json格式