jsonobject for nested api's put operation - json

i am trying to put request by using jsonobject but i couldnt find a way to send it
how can i create put body for api like
{
"roleRight": {
"systemSetting": 0,
"userManagement": 0
}
}
right now, i created like;
public static JSONObject nspRightSet(String ssvalue, String umvalue) {
JSONObject requestParams = new JSONObject();
requestParams.put("roleRight.systemSetting", ssvalue);
requestParams.put("roleRight.userManagement", umvalue);
return requestParams;
}
and use it by;
res = given()
.header("Authorization", "Bearer " + localLogin.accessToken)
.header("Content-type", "application/json")
.contentType(ContentType.JSON)
.body(nspRightSetBody)
.when()
.put("https://localhost:8090/api/v1/roles/" + rolenameId + "/right")
.then()
.log().all()
.statusCode(201)
.extract()
.response().getBody();
}
but it gives error like;
"error": "JSON parse error: Cannot deserialize instance of `...` out of START_ARRAY token;

public static JSONObject nspRightSet(String ssvalue, String umvalue) {
JSONObject requestParams = new JSONObject();
JSONObject childJSON = new JSONObject();
childJSON.put("systemSetting", ssvalue);
childJSON.put("userManagement", umvalue);
requestParams.put("roleRight", childJSON);
return requestParams;
}

Related

How to add attachment using TestRail API?

public static void fnUpdateResultToTestRail(String trusername, String trpassword, String trRunId,String testCaseName,String status, String testStepDetails)
throws MalformedURLException, IOException, APIException {
APIClient client = new APIClient("testrailurl");
client.setUser("username");
client.setPassword("password");
HashMap data = new HashMap();
data.put("status_id", status);
data.put("comment", testStepDetails);
HashMap data1 = new HashMap();
data1.put("attachment","C:\\Pictures\\\\X-SecurityToken-Issue.jpg";
JSONArray array = (JSONArray) client.sendGet("get_tests/"+trRunId);
//System.out.println(array.size());
for (int i = 0; i < array.size(); i++) {
JSONObject c = (JSONObject) (array.get(i));
String testrailTestCaseName=c.get("title").toString();
if (testrailTestCaseName.equals(testCaseName)) {
System.out.println(c.get("id"));
client.sendPost("add_result/" + c.get("id"), data);
client.sendPost("add_attachment_to_case/"+c.get("case_id"), data1);
break;
}
}
}
TestRail API returned HTTP 400("No file attached or upload size was exceeded.")
As per document, we need to pass Headers: { "Content-Type","value":"multipart/form-data" }
API client has inbuilt methods....
public Object sendPost(String uri, Object data)
throws MalformedURLException, IOException, APIException
{
return this.sendRequest("POST", uri, data);
}
private Object sendRequest(String method, String uri, Object data)
throws MalformedURLException, IOException, APIException
{
URL url = new URL(this.m_url + uri);
...........
}
How to add the header in this inbuilt method on run time..?
Can any one help on this?

parsing JSON using "koush/ion" not working?

*the JsonObject json is empty, but result in onCompleted function works fine and correctly returns json data but I can't use it outside the oncompleted function *
final JsonObject json = new JsonObject();
Ion.with(MainActivity.this)
.load("https://wordsapiv1.p.mashape.com/words/" + searchedWord)
.setHeader("X-Mashape-Key","I've hidden the Key !")
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
Log.i("result: ","" + result);
Log.i("json: ", "" + json);
}
});
I don't understand why you need the first line?
final JsonObject json = new JsonObject();

Android Volley POST body request recieved EMPTY at backend

i'm using the following code to post a json object to php server :
Map<String, String> paramsMap = new HashMap<String, String>();
paramsMap.put("tag", "jsonParams");
JSONObject jsonObject = new JSONObject(paramsMap);
Log.d("JSON", jsonObject.toString());
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("JSON RESPONSE", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JSON ERROR", error.getMessage());
}
});
requestQ.add(jsonRequest);
and using this to receive the object in php:
$body = '';
$handle = fopen('php://input','r');
while(!feof($handle)){
$body .= fread($handle,1024);
}
$logger->log("login request","request body: ".$body);
the problem is that the $body is always empty i used FIDDLER to check my HTTP request and it's there as raw data like this : {"tag":"jsonParams"}
so what am i messing ?
thx in advance.
I know this is an old question, but for future readers...
I have solved the exact same problem by using StringRequest instead of JsonObjectRequest. The constructor differs just very slightly and you can then easily parse string response to JsonObject like this:
JSONObject response = new JSONObject(responseString);
Not sure what was your problem, but for the future googlers:
My problem was that I wasn't reading from php://input
Full code (working):
Java:
JSONObject jsonobj; // declared locally so that it destroys after serving its purpose
jsonobj = new JSONObject();
try {
// adding some keys
jsonobj.put("new key", Math.random());
jsonobj.put("weburl", "hashincludetechnology.com");
// lets add some headers (nested JSON object)
JSONObject header = new JSONObject();
header.put("devicemodel", android.os.Build.MODEL); // Device model
header.put("deviceVersion", android.os.Build.VERSION.RELEASE); // Device OS version
header.put("language", Locale.getDefault().getISO3Language()); // Language
jsonobj.put("header", header);
// Display the contents of the JSON objects
display.setText(jsonobj.toString(2));
} catch (JSONException ex) {
display.setText("Error Occurred while building JSON");
ex.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, URL, jsonobj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("onResponse()");
try {
result.setText("Response: " + response.toString(2))
System.out.println("Response: " + response.toString(2));
} catch (JSONException e) {
display.setText("Error Occurred while building JSON");
e.printStackTrace();
}
//to make sure it works backwards as well
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("onErrorResponse()");
System.out.println(error.toString());
}
});
System.out.println("After the request is made");
// Add the request to the RequestQueue.
queue.add(jsObjRequest);
Clarification: display and result are two TextView objects I am using to display data on the screen, and queue is Volley's request queue.
PHP:
$inp = json_decode(file_get_contents('php://input')); //$input now contains the jsonobj
echo json_encode(["foo"=>"bar","input"=>$inp]); //to make sure we received the json and to test the response handling
Your Android Monitor should output sth. like :
{
"foo":"bar",
"input":{
"new key":0.8523024722406781,
"weburl":"hashincludetechnology.com",
"header": {
"devicemodel":"Android SDK built for x86",
"deviceVersion":"7.1",
"language":"eng"
}
}
}

Apache HttpClient JSON Post

I try to send directly a JSON string with HttpClient 4.4 in an application (SWT/JFace) :
public String postJSON(String urlToRead,Object o) throws ClientProtocolException, IOException {
String result="";
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost postRequest = new HttpPost(urlToRead);
postRequest.setHeader("content-type", "application/x-www-form-urlencoded");
//postRequest.setHeader("Content-type", "application/json");
//{"mail":"admin#localhost", "password":"xyz"}
String jsonString=gson.toJson(o);
StringEntity params =new StringEntity(jsonString);
params.setContentType("application/json");
params.setContentEncoding("UTF-8");
postRequest.setEntity(params);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
}finally {
httpClient.close();;
}
return result;
}
I try to get the response from the server (Apache/PHP) with $POST
the correct content of $POST should be :
array("mail"=>"admin#localhost","password"=>"xyz")
When I use content-type : application/x-www-form-urlencoded
$POST content is :
array( "{"mail":"admin#localhost","password":"xyz"}"=> )
When I use content-type : application/json
$POST is empty : array()
Is there a way to post the JSON string with HttpClient or should I use an ArrayList<NameValuePair> and add each member of my object in the entity ?
I put the "NameValuePair" solution (not in the comments, the answer is too long), but I thought StringEntity was able to understand the JSON see How to POST JSON request using Apache HttpClient? and there: HTTP POST using JSON in Java
public String postJSON(String urlToRead,Object o) throws ClientProtocolException, IOException {
String result="";
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost postRequest = new HttpPost(urlToRead);
postRequest.setHeader("content-type", "application/x-www-form-urlencoded");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//{"mail":"admin#localhost", "password":"xyz"}
JsonElement elm= gson.toJsonTree(o);
JsonObject jsonObj=elm.getAsJsonObject();
for(Map.Entry<String, JsonElement> entry:jsonObj.entrySet()){
nameValuePairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue().getAsString()));
}
postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
}finally {
httpClient.close();;
}
return result;
}
This way, the content of $POST is correct : array("mail"=>"admin#localhost","password"=>"xyz")

return ModelAndView when JSON is returned

Can we return JSON object from spring controller and write that JSON object on jsp page.
Below is my jsp page:
<script type="text/javascript">
dojo.require("dojox.grid.EnhancedGrid");
dojo.require("dojox.data.QueryReadStore");
dojo.ready(function(){
mystore=new dojo.data.ItemFileReadStore({url:"<%=request.getContextPath()%>/showData.htm"});
var layout= [
{field: 'ID', name: 'SID',formatter: hrefFormatter,datatype:"number" },
{field: 'SPREAD',name: 'SPREAD',autoComplete: true}
]
var grid = new dojox.grid.EnhancedGrid({
id: 'myGrid',
----
});
</script>
Controller:
#RequestMapping(value = "/showData", method = RequestMethod.GET)
public void getSTIDData(HttpServletRequest request,
HttpServletResponse response, #ModelAttribute VINDTO vinData,
BindingResult beException) throws IOException {
try {
......
......
XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});
xstream.alias("items", com.loans.auto.DTO.VINRequestDTO.class);
String str = xstream.toXML(vinListCopy);
StringBuffer rowData = new StringBuffer();
rowData.append("{'numRows':").append(vinListCopy.size())
.append(",'items':").append(str).append("}");
PrintWriter out = response.getWriter();
out.print(rowData);
}
Instead of getSTIDData(..) returning void , i want this method to return ModelAndView object, but when i return ModelAndView object, in jsp page data is not getting loaded and it says "NO Data Found". Please suggest. Thanks.
Below is the exception generated when i used Gson
SyntaxError {stack: "SyntaxError: Unexpected identifier↵ at Object.d… at signalWaiting (/MYWebProject/dojo/Deferred.js:28:4)", message: "Unexpected identifier"}
message: "Unexpected identifier"
stack: "SyntaxError: Unexpected identifier↵ at Object.dojo.fromJson (/MYWebProject/dojo/_base/json.js:26:23)↵ at Object.dojo._contentHandlers.dojo.contentHandlers.json (/MYWebProject/dojo/_base/xhr.js:78:16)↵ at Object.dojo._contentHandlers.dojo.contentHandlers.json-comment-optional (/MYWebProject/dojo/_base/xhr.js:156:28)↵ at _deferredOk (/MYWebProject/dojo/_base/xhr.js:432:42)↵ at notify (/MYWebProject/dojo/_base/Deferred.js:187:23)↵ at complete (/MYWebProject/dojo/_base/Deferred.js:168:4)↵ at resolve.callback (/MYWebProject/dojo/_base/Deferred.js:248:4)↵ at eval (/MYWebProject/dojo/_base/xhr.js:627:8)↵ at signalListener (/MYWebProject/dojo/Deferred.js:37:21)↵ at signalWaiting (/MYWebProject/dojo/Deferred.js:28:4)"
__proto__: Error
yes you can return as JSON response.showing with the help of Gson API
#RequestMapping(value = "/showData", method = RequestMethod.GET)
public #ResponseBody String getUserHomePage(HttpServletRequest request,HttpServletResponse response, #ModelAttribute VINDTO vinData,BindingResult beException) throws IOException {
//you code stuff to create model object bean
Gson gson = new Gson();
return gson.toJson(objectBean);
}
Keep it clean and simple...
Here is a real life snippet of code ...
#RequestMapping(value = "/actions/getImplGroups", method = RequestMethod.POST)
public ResponseEntity<String> getImplGroups(HttpServletRequest request, HttpServletResponse response) {
List<String> groups = bpmClient.getAllGroups();
ObjectMapper mapper = new ObjectMapper();
String jsonString;
try {
jsonString = mapper.writeValueAsString(groups);
} catch (JsonGenerationException e) {
jsonString = "Error with json generation: " + e.getMessage();
} catch (JsonMappingException e) {
jsonString = "Error with json mapping: " + e.getMessage();
} catch (IOException e) {
jsonString = "Error with json: " + e.getMessage();
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(jsonString, responseHeaders, HttpStatus.CREATED);
}
The important point to consider is sending the correct web header, so that your page expects to see json.
I the case above we used the Jackson library to create the json, but in truth you could format the json any way you like. Here is an example of a simple, manually formatted string...
#RequestMapping(value = "/actions/getTicketsNotUpdatedWithinShift", method = RequestMethod.POST)
public ResponseEntity<String> getTicketsNotUpdatedWithinShift(String center, String sections, String minutesInShift, Model model) {
String[] sectionArray = sections.split(",");
String json = "";
String rowsString = "";
for (String section : sectionArray) {
List<Map<String, String>> rows = service.getMinutesSinceLastTicketUpdate(center, section);
for (Map<String, String> row : rows) {
int minutesSinceUpdate = Integer.parseInt(row.get("minutes"));
if (minutesSinceUpdate > Integer.parseInt(minutesInShift)) {
String description = row.get("description");
rowsString = rowsString + "\"" + description + "\",";
}
}
}
// Build the json structure
if (!rowsString.isEmpty()) {
// Trim the trailing comma.
rowsString = rowsString.replaceAll(",$", "");
json = "[" + rowsString + "]";
} else {
json = "[]";
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}