I am using GSON library to read JSON file for my automation. For which I need to read file and then create a object of json while traversing the JSON.

Later I am using these objects to to modify the JSON.. I want to reduce the code for traversing down the json as many objects are getting created.

Though this works perfectly fine. Just I need to modularize the code.

Adding the code with the URL , Response and User JSON

Url.json

{"users":
{"addUser": "<URL>/addUser","editUser": "<URL>/editUser"}
}

Response .json

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

User.json

{

"addUsers":
{"userAttributes":{  
  "lst":"lastname",
  "id":"username",
  "Password":"password"
}
},
"updateUsers":

{ "userAttributes":{  
 "Password":"password"
}}}

Java Code

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")


}
}

ReadGSON.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;

}

Actual Currently I am creating multiple objects to read ths jOSN file and later with the use of same I am updating my JSON.

Expected Can I modularize this approach of code.

1 Answers

0
Starmixcraft On

Yes you can:

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
}
}