gpt4 book ai didi

java - 如何解析和编码 GraphQL 对 Java POJO 的响应?

转载 作者:搜寻专家 更新时间:2023-11-01 00:54:19 25 4
gpt4 key购买 nike

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?

是否有一组更好的库可以帮助我使用 Java 解析/编码 GraphQL?

顺便说一下,第三方服务器不提供 GraphQL 模式文件......

最佳答案

如果您只需要生成这些类一次并在以后的每次调用中使用它们,那么您可以下载一个 JSON 到 POJO 的映射工具。有很多可用的实用程序;只是在快速搜索中,我找到了几个选项:

一旦你有了 POJO 类,你就可以使用标准的 jackson 映射器来获取类

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

关于java - 如何解析和编码 GraphQL 对 Java POJO 的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50360295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com