我正在使用GSON库来读取JSON文件以实现自动化。我需要读取文件,然后在遍历JSON时创建json的对象。
后来我使用这些对象来修改JSON ..我想减少遍历json的代码,因为很多对象都是在创建的。
虽然这很好用。我需要模块化代码。
使用URL,响应和用户JSON添加代码
Url.json
{"users":
{"addUser": "<URL>/addUser","editUser": "<URL>/editUser"}
}
回复.json
[
{"success":true},
{"success":false}
]
User.json
{
"addUsers":
{"userAttributes":{
"lst":"lastname",
"id":"username",
"Password":"password"
}
},
"updateUsers":
{ "userAttributes":{
"Password":"password"
}}}
Java代码
public class UsersSameFile extends ReaderUtil{
JsonObject userjs = JsonReaderUtil.readGSONObject("./requestJson/User.json");
JsonObject urljs = JsonReaderUtil.readGSONObject("./urlsJson/Url.json");
JsonArray res = JsonReaderUtil.readGSONArray("./responseJson/response.json");
JsonObject addUsers = userjs.get("addUsers").getAsJsonObject();
JsonObject userAttributes = addUsers.get("userAttributes").getAsJsonObject();
JsonObject usersurl = urljs.get("users").getAsJsonObject();
JsonObject success = res.get(0).getAsJsonObject();
@Given("^Add a user$")
public void add_a_user_json_payloads() throws Throwable {
userAttributes.addProperty("lst", getValue("UserOne"));
userAttributes.addProperty("id",getValue("UserOne"));
userAttributes.addProperty("Password",getValue("password"));
System.out.println(addUsers);
System.out.println("This returns me the updated JSON. How can i reduce the code at class level for reading in JSON objects from file. I am using this for API automation")
}
}
read GS on.Java
public static JsonObject readGSONObject(String file) {
try {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
File jsonFile = new File(file);
String jsonString = FileUtils.readFileToString(jsonFile);
JsonElement jelement = new JsonParser().parse(jsonString);
JsonObject jobj=jelement.getAsJsonObject();
return jobj;
} catch (FileNotFoundException e) {
// TODO: handle exception
}
catch (IOException e) {
// TODO: handle exception
}
return null;
}
实际当前我正在创建多个对象来读取jSON文件,稍后使用相同的我正在更新我的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
}
}