0

My Json looks something like this:

{
"source": "somedatabasename",
"lisofobjects": [{
    "data": {
        "starttime": "145756767377",
        "age": "20",
        "name": "xyz"
    }
}]

}

As a part of validation of my API I want to pass string in age attribute for example age: "xyz". I have created a POJO objects and parsing json using gson.I want to know how should I setvalueof age at runtime.So my request code looks like this:

 protected RequestSpecification abc(classnamefromwherejsonisparsed object)
            throws JsonSyntaxException, FileNotFoundException, IOException {
            RequestSpecBuilder builder = new RequestSpecBuilder();

            builder.setContentType(ContentType.JSON); 
            builder.setBody(object.toJson(object.getallTestData()));

Thus here with getallTestData I want to change only 1 value for example age here. something like object.setAge("abc")

Techie
  • 21
  • 7
  • I'm not sure I follow exactly. You mention that you have a POJO: can't you simply call `setAge(42)` on that object, and then serialize it (or the object that contains it) to JSON? – ck1 Jun 18 '16 at 01:04
  • I ca call setAge(24) but the thing is I am not getting how I wil call as I am passing object to jsonbody like this builder.setBody(object.toJson(object.getallTestData())) and not sure how to override value of setAge from an existing JSON – Techie Jun 18 '16 at 01:23

1 Answers1

2

If I understand you correctly you need to generate different invalid test data from sample json. In that case this coud work:

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

...

String json =
        "{\n" +
        "\"source\": \"somedatabasename\",\n" +
        "\"lisofobjects\": [{\n" +
        "    \"data\": {\n" +
        "        \"starttime\": \"145756767377\",\n" +
        "        \"age\": \"20\",\n" +
        "        \"name\": \"xyz\"\n" +
        "    }\n" +
        "}]" +
        "}";

JsonParser parser = new JsonParser();
JsonObject rootObject = parser.parse(json).getAsJsonObject();

JsonObject firstData = rootObject.getAsJsonArray("lisofobjects")
        .get(0).getAsJsonObject().getAsJsonObject("data");
firstData.remove("age");
firstData.addProperty("age", "abc");

String modifiedJson = new Gson().toJson(rootObject);