首页 > 解决方案 > How to get json from GraphQL

问题描述

Hi I'm making a bridge that translates GraphQL's otherwise query to another service. I had the idea to take json from a query to GraphQL and make the query via resttemplate. But I couldn't find a way to take the request body. I will be glad to see an example of your code or another more competent solution.

STACK: Spring boot+ java 8 + graphql

@Component
public class VehicleQuery implements GraphQLQueryResolver {

    @Autowired
    private VehicleService vehicleService;

    public List<Vehicle> getVehicles(final int count) {
        return this.vehicleService.getAllVehicles(count);
    }

    public Optional<Vehicle> getVehicle(final int id) {
        return this.vehicleService.getVehicle(id);
    }
}

标签: javaspringspring-bootgraphql

解决方案


创建一个JsonObject实例。将您的查询添加到属性。将变量添加到同一个对象。

JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("query", query);
jsonObject.add("variables", variables);

在您的 java 代码中调用查询,如下所示:

HttpResponse<String> httpResponse = post(jsonObject.toString());

推荐阅读