Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a Graphql query into a Java object

Tags:

java

graphql

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 :)

like image 334
Jeff Avatar asked Feb 23 '26 22:02

Jeff


1 Answers

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    }  }}");
like image 55
Jeff Avatar answered Feb 27 '26 02:02

Jeff