Jeff
Jeff

Reputation: 407

How to parse a Graphql query into a Java object

I need to do some pre-parsing steps before executing a Graphql query. But I have no idea how to convert an input Graphql query, which is a String, into a Java Object. Ideally, the Java object should contain the subfields and the arguments of each field of the query. For example:

{
  Instrument(id: "1234") {
    Reference {
      Name
    }
  }
}

This may be converted into something like a JSON object:

{
  "Instrument":{
    "arguments:{
      "id": "1234"
    }
    "fields":{
      "Reference":{
        "fields":{
          "Name": "String"
        }
      }
    }
  }
}

Any help is highly appreciated :)

Upvotes: 3

Views: 5764

Answers (1)

Jeff
Jeff

Reputation: 407

Below code just parse the GraphQL query grammar, even without knowing the schema.

import graphql.language.Document;
import graphql.parser.Parser;
Parser parser = new Parser(); 
Document document = parser.parseDocument("{  Instrument(id: \"1234\") {    Reference {      Name    }  }}");

Upvotes: 4

Related Questions