如何模块化 JsonObject 和 JsonArray 的代码以在类级别读取 Json 文件.我稍后会用它来编写测试用



我正在使用GSON库来读取JSON文件以进行自动化。为此,我需要读取文件,然后在遍历 JSON 时创建一个 json 对象。

稍后我使用这些对象来修改 JSON。 我想减少遍历 json 的代码,因为正在创建许多对象。

虽然这很好用。只是我需要模块化代码。

添加带有 URL、响应和用户 JSON 的代码

网址.json

{"emplyee":
{"addemplyee": "<URL>/emplyee","addemplyee": "<URL>/editemplyee"}
}

响应 .json

[
{"success":true},
{"success":false}
]

emplyee.json

{
"addemplyee":
{"details":{  
"lst":"lastname",
"id":"username",
"Password":"password"
}
},
"editemplyee":
{ "details":{  
"Password":"password"
}}}

实际目前我正在创建多个对象来读取 jOSN 文件,稍后使用相同的对象,我正在更新我的 JSON。

预期我可以模块化这种代码方法吗?

是的,你可以:

public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); //you can reuse gson as often as you like
public <T> static T readJson(String file){
try{
FileReader fr = new FileReader(new File(file)); //gson takes a filereader no need to load the string to ram
T t = GSON.fromJson(fr, T.getClass());
fr.close(); //close the reader
return t;
}catch(Error e){
//ignore or print, if you need
}
}

最新更新