1

I have developed a tool that can test some requests to a server, the requests themselves are no more than some simple JSON files that are stored on the disc and can be added continuously, but ... there is one more thing, the JSON files contains an e-mail address that needs to be changed upon running the project each time, this is because each of users have a personal e-mail, I made that because server can't accept more than one request from an user. So I am looking for a solution to inject this e-mail address dynamically into JSON.

I'm using Java for this, and also jayway for REST API and Gson for JSONs. So far I looked into google, but can't find anything at all.

Ferrago
  • 83
  • 1
  • 6
  • How are you loading the JSON? If you're loading it in its entirity, you could use java.util.Formatter to do this. – Jeff Watkins Jan 26 '15 at 13:22
  • You could do this by these solutions: - Use json file as template string with markup like "{email: ${e-mail}}", then just use ```jsonTemplate.replace("${e-mail", email[i])``` - parse json to Map or Object that model request, then change email field and build again json out of it – Mati Jan 26 '15 at 13:27
  • @JeffWatkins I'm loading it as `jsonFixture(jsonPath);` @Mati ok, I'm trying this right now – Ferrago Jan 26 '15 at 14:02
  • @Mati it works, you can add your answer and I will accept it. Thanks guys. – Ferrago Jan 26 '15 at 14:12
  • Parse the JSON into Maps/Lists, update as needed, serialize. – Hot Licks Jan 26 '15 at 17:06

2 Answers2

3

You could do this by these solutions:

  • Use json file as template string with markup like "{email: ${e-mail}}", then just use jsonTemplate.replace("${e-mail}", email[i])
  • parse json to Map or Object that model request, then change email field and build again json out of it
Mati
  • 2,476
  • 2
  • 17
  • 24
1

Use Gson.

    Gson gson = new Gson();

    String yourJsonInStringFormat = " {\"email\":placeHolder,\"password\":\"placeHolder\"}";

    Map map = gson.fromJson(yourJsonInStringFormat, Map.class);

    map.put("email", "jose@com.com");
    map.put("password", "123456");
    String newJson = gson.toJson(map);
    System.out.println(newJson);

This prints out:

{"email":"jose@com.com","password":"123456"}

The fields being injected do not need to be there already. For example this also works:

    Gson gson = new Gson();

    String yourJsonInStringFormat = "{}";

    Map map = gson.fromJson(yourJsonInStringFormat, Map.class);

    map.put("email", "jose@com.com");
    map.put("password", "123456");
    String newJson = gson.toJson(map);
    System.out.println(newJson);
Jose Martinez
  • 11,452
  • 7
  • 53
  • 68