I currently have a graphQL endpoint that has a request body with two json objects, variables and query. The request body should look like below:
{
"variables": {},
"query": "{n uploadQueueSummary {n fileNamen createdByn salesIdn completedRowsn totalRowsn uploadUUIDn uploadTimen statusn hasErrorsn uploadTypen demandTypen errorRowsn deletedRowsn failedRowsn }n}"
}
When I use the below code, the variables object value is coming as a String instead, regardless if hard-coded or get from POJO:
GraphQLQuery queryAndVars = new GraphQLQuery() //POJO class
JSONObject requestBody = new JSONObject;
requestBody.put("query",queryAndVars.getQuery());
requestBody.put("variables", "{}");
The request body is as below after I run my code:
{
"variables": "{}",
"query": "{n uploadQueueSummary {n fileNamen createdByn salesIdn completedRowsn totalRowsn uploadUUIDn uploadTimen statusn hasErrorsn uploadTypen demandTypen errorRowsn deletedRowsn failedRowsn }n}"
}
How can I set the JSONObject key (variables) value without treating it as a String?
3
Rather than string {} , pass it as new JSONObject()
Replace your line :
requestBody.put("variables", "{}");
with this :
requestBody.put("variables", new JSONObject());
You should try this
GraphQLQuery queryAndVars = new GraphQLQuery() //POJO class
JSONObject requestBody = new JSONObject();
requestBody.put("query",queryAndVars.getQuery());
requestBody.put("variables", new JSONObject());
in Json {} is the representation of an object.
0
I think instead of using “{}” string, you can simply replace it with new Object() or new JSONObject() as follows:
requestBody.put("variables", new Object());
OR
requestBody.put("variables", new JSONObject());
Prasoon Balara is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.