skip to Main Content

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

Answers


  1. 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.

    Login or Signup to reply.
  2. Rather than string {} , pass it as new JSONObject()

    Replace your line :

    requestBody.put("variables", "{}");
    

    with this :

    requestBody.put("variables", new JSONObject());
    
    Login or Signup to reply.
  3. 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());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search