2017-03-09 100 views
1

我有一個使用Google Gson創建的JsonObject。如何使用放心的發送請求在主體中發送JsonObject?

JsonObject jsonObj = gson.fromJson(response1_json, JsonElement.class).getAsJsonObject(); 

此外,我做了一些修改,如下現有jsonobj:

JsonObject newObject = new JsonObject(); 
      newObject.addProperty("age", "50"); 
      newObject.addProperty("name", "X"); 
jsonObj.get("data").getAsJsonArray().add(newObject); 

現在,使用放心,我需要發送此JSONObject的POST請求。我嘗試了以下但它不起作用,並拋出異常:

Response postResponse = 
        given() 
      .cookie(apiTestSessionID) 
      .header("Content-Type", "application/json") 
      .body(jsonObj.getAsString()) 
      .when() 
      .post("/post/Config"); 

請指導我這一點。

+0

你可以發佈你所得到的例外呢? – Uttam

+0

嘗試添加.contentType(「應用程序/ json」),而不是將其設置爲標題 – Uttam

回答

1

嘗試下面的代碼中使用,以JSON發送到POST請求休息,保證

//Get jsonObject from response 
JsonObject jsonObj = gson.fromJson(response1_json, JsonElement.class).getAsJsonObject(); 


//Create new jsonObject and add some properties 
JsonObject newObject = new JsonObject(); 
    newObject.addProperty("age", "50"); 
    newObject.addProperty("name", "X"); 

//Get jsonarray from jsonObject 
JsonArray jArr = jsonObj.get("data").getAsJsonArray(); 

//Add new Object to array 
jArr.add(newObject); 

//Update new array back to jsonObject 
jsonObj.add("data", jArr); 

Response postResponse = 
       given() 
     .cookie(apiTestSessionID) 
     .contentType("application/json") 
     .body(jsonObj.toString()) 
     .when() 
     .post("/post/Config"); 
+1

它爲我工作謝謝..我用contentType(applicaiton/json),它解決了我的問題。 – ButterSkotch