Search code examples
javaspring-bootgraphql

Return specified JSON format using Graphql and Java


Expected JSON response

{
    "sample-event": "test event",
    "sample-id": "123"
}

Actual JSON response

{
    "sampleEvent": "test event",
    "sampleId": "123"
}

This is the type of mutation to send JSON payload to an API for further processing

GraphQL Schema

type Mutation{
   sampleRequest( addDataInput: AddDataInput! ) : SampleResponse @hasScope(scopes: [insert])
}

input SampleRequest{
  sampleEvent : String
  sampleId : String
}

Models

@Data
@Getter
@Setter
public class SampleRequest{
  private String sampleEvent;
  private String sampleId;
}

Request.java

public SampleResponse SendPayload (SampleRequest sampleRequest){
    UriComponents uri = UriComponentsBuilder.fromUriString(properties.getUrl() + ENDPOINT_NAME).build();
    HttpEntity<SampleRequest> entity = new HttpEntity<>(sampleRequest, header);
    HttpStatusCode statusCode = restTemplate.exchange(uri.toString(), HttpMethod.POST, entity, HttpResponse.class).getStatusCode(); 
    SampleResponse response = new SampleResponse();
    response.setStatus(statusCode.toString());  
    return statusCode;
}

How to get the expected JSON response that has the key as sample-event and sample-id?


Solution

  • If you're using Jackson (Spring Boot uses it, so I think you are) you can annotate your fields with @JsonProperty to override the generated name.

    @Data
    @Getter
    @Setter
    public class SampleRequest{
      @JsonProperty("sample-event")
      private String sampleEvent;
    
      @JsonProperty("sample-id")
      private String sampleId;
    }
    

    JavaDoc

    Spring boot docs on Jackson