Search code examples
graphql-javagraphql-schema

How to assign a JSONObject value to a field in graphql schema file?


I am working on an application with graphQL and spring boot framework. Here I am using GraphQL's Schema-first approach to write my schema details. In my scenario, I need to assign JSONObject and JSONArray as input to few of the fields in my Schema file. In graphQL schema file, we can not directly set JSONObject/JSONArray as data types. Can someone please guide me on how to handle JSONObject/JSONArray in graphQL?


Solution

  • You can define your own scalar type JSON:

    scalar JSON
    
    type Foo {
      field: JSON
    }
    

    Then implement a new java GraphQLScalarType bean:

    @Component
    public class JSONScalarType extends GraphQLScalarType {
    
      JSONScalarType() {
        super("JSON", "JSON value", new Coercing<Object,Object>() {
            ...
        });
      }   
    }
    

    Finally implement the scalar Coercing. You can find a tutorial on scalar types here https://www.graphql-java.com/documentation/v15/scalars/

    Or, as in graphql a JSON is an object, you can have a look at how the graphql-java-extended-scalars implemented the Object and JSON scalars : https://github.com/graphql-java/graphql-java-extended-scalars/blob/master/src/main/java/graphql/scalars/object/ObjectScalar.java

    Another solution would be to use the graphql-java-extended-scalars library: https://github.com/graphql-java/graphql-java-extended-scalars