2016-06-17 43 views
0

的json看起來是這樣的:在Java運行時更改的JSON的屬性值1

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

}

由於我的API驗證的一部分,我想通過串年齡屬性,例如年齡:「xyz」。我創建了一個POJO對象和解析使用gson.I想知道我應該怎麼setvalueof年齡runtime.So我的請求的代碼看起來像這樣JSON:

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

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

因此這裏getallTestData我想換隻值1例如這裏的年齡。像object.setAge(「abc」)

+0

我不確定我是否按照。你提到你有一個POJO:你不能簡單地在該對象上調用'setAge(42)',然後將它序列化(或包含它的對象)到JSON? – ck1

+0

我可以調用setAge(24),但事情是我沒有得到如何我打電話,因爲我傳遞對象到像這樣的builder.setBody(object.toJson(object.getallTestData())),並不知道如何覆蓋來自現有JSON的setAge的值 – Techie

回答

0

如果我正確理解你,你需要從樣本json生成不同的無效測試數據。 在這種情況下,這coud工作:

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