0

I have a json file which looks like

{
  name = VARIABLE1
  age = VARIABLE2
  address
  {
    street = VARIABLE3
    line = VARIABLE4
  }
}

So now i want to read the file in java code and generate the values of VARIABLES and generate the json and post it to a server. Which means i am testing the server with same kind of data but with different values.

How can i do this

venkat sai
  • 455
  • 9
  • 30

2 Answers2

1

What you have provided in the question is not a well formed json. Ignoring that, you can read a well formed json string into a JSONObject, and replace the values as you want :

private static String getData(String name, int age, String street, String line) throws JSONException {
    JSONObject jsonObject = new JSONObject("{  name : VARIABLE1,  age : VARIABLE2,  address : { street : VARIABLE3,    line : VARIABLE4  }}");
    JSONObject address = (JSONObject) jsonObject.get("address");
    jsonObject.put("name", name);
    jsonObject.put("age", age);
    address.put("street", street);
    address.put("line", line);
    return jsonObject.toString();
}

You can call this method as :

getData("Random", 20, "str", "lin");
Gautam
  • 1,862
  • 9
  • 16
0

You can use a specific Java object containing all the fields you want (with simple getters and setters) and transform it to Json using whatever library you prefer (ex. Gson, Jackson...). Alternatively, if your Json String is very simple, you can write it by hand and use String.format for replacing the variable values.