GraphQL的新手......
将GraphQL查询发送到由第三方控制的外部服务器。
使用此GraphQL查询:
query Photos($first: Int!, $propertyId: String) {
viewer {
content {
contentLists(first: $first, property_id: $propertyId, contentListType: IMAGE, publishState: PUBLISHED, orderBy: originalPublishDate, orderByDirection: DESC) {
edges {
node {
id
title
caption
originalPublishDate
lastModifiedDate
contents(first: $first) {
edges {
node {
id
title
caption
type
... on Image {
asset {
createdDate
lastModifiedDate
id
url
title
height
width
}
}
}
}
}
}
}
}
}
}
}
查询变量:
{
"propertyId" : "23456832-7862-5679-4342-415f32385830",
"first": 20
}
使用此代码段,我可以向外部服务器发送查询:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+accessToken);
HttpEntity<String> entity = new HttpEntity<String>(request,headers);
String response = restTemplate.postForObject(EXTERNAL_URL, entity, String.class);
收到以下回复:
{
"data": {
"viewer": {
"content": {
"contentLists": {
"edges": [
{
"node": {
"id": "3510e8f7-452s-f531-43b0-ac36ba979e5a9f4m",
"title": "Homer Simpson goes Camping",
"caption": "Homer Simpson goes Camping",
"originalPublishDate": "2018-02-18T03:31:56.352Z",
"lastModifiedDate": "2018-02-18T03:32:13.530Z",
"contents": {
"edges": [
{
"node": {
"id": "3506d951-1332-86fg-42bc-b11183db50394f40",
"title": "No Title",
"caption": "",
"type": "IMAGE",
"asset": {
"createdDate": "2018-02-18T03:31:38.406Z",
"lastModifiedDate": "2018-02-18T03:31:38.991Z",
"id": "65037262-7169-7065-7861-7035676a6f65323467617866",
"url": "",
"title": "No Title",
"height": null,
"width": null
}
}
}
]
}
}
}
]
}
}
使用这些Java库:
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java</artifactId>
<version>8.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>5.0.0</version>
</dependency>
如何编组对POJO的POJO和/或ArrayList的响应?
是否有更好的lib可以帮助我使用Java解析/编组GraphQL?
顺便说一下,第三方服务器不提供GraphQL架构文件......
答案 0 :(得分:0)
如果您只需要生成一次这些类并在之后的每次调用中使用它们,那么您可以将JSON下载到POJO映射工具。有很多可用的实用程序;只是在快速搜索中我找到了几个选项:
获得POJO课程后,您可以使用标准的杰克逊映射器获取课程
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer "+accessToken);
HttpEntity<String> entity = new HttpEntity<String>(request,headers);
String rawResponse = restTemplate.postForObject(EXTERNAL_URL, entity, String.class);
ObjectMapper objectMapper = new ObjectMapper();
PhotoQueryResponse response = objectMapper.readValue(rawResponse, PhotoQueryResponse.class);
答案 1 :(得分:0)
你可以查看这个名为
的java库Glitr (GraphQL to Java)以及here中的手册。
这是它支持的甜蜜类型,
GraphQLString String
GraphQLBoolean Boolean
GraphQLInt Integer
GraphQLFloat Float
GraphQLObjectType Any POJO
GraphQLInterfaceType Any interface type
GraphQLUnionType Not supported
GraphQLEnumType Any enum type
GraphQLInputObjectType Any POJO
GraphQLList Any implementing class of Collection
GraphQLNonNull See @GlitrNonNull