本文介绍了返回HashMap< String,Object>来自GraphQL-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试了几种变体,没有运气在GraphQL中返回地图.所以我有以下两个对象:
I tried few variant and had no luck to return a map in GraphQL. So I have the following two objects:
public class Customer {
private String name, age;
// getters & setters
}
public class Person {
private String type;
private Map<String, Customer> customers;
// getters & setters
}
我的模式如下:
type Customer {
name: String!
age: String!
}
type Person {
type: String!
customers: [Customer!] // Here I tried all combination but had no luck, is there a Map type support for GQL?
}
有人可以告诉我如何实现此目标,以便GraphQL神奇地处理此目标或替代方法.
Can someone please tell me how to achieve this so that GraphQL magically process this or an alternative approach.
非常感谢!
推荐答案
以防万一-您始终可以将地图对象表示为JSON字符串(对我来说是有帮助的).
Just in case - you can always represent map object as a JSON string (in my case it was helpful).
public class Person {
private String type;
private Map<String, Customer> customers;
// getters & setters
}
将会
type Person {
type: String!
customers: String!
}
此后,别忘了添加数据提取程序以将其转换为JSON.
After that don't forget to add data fetcher to convert it to the JSON.
public DataFetcher<String> fetchCustomers() {
return environment -> {
Person person = environment.getSource();
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(person.getCustomers());
} catch (JsonProcessingException e) {
log.error("There was a problem fetching the person!");
throw new RuntimeException(e);
}
};
}
它将返回:
"person": {
"type": "2",
"customers": "{\"VIP\":{\"name\":\"John\",\"age\":\"19\"},\"Platinum VIP\":{\"name\":\"Peter\",\"age\":\"65\"}}"
}
此后,您可以像处理客户端中的典型JSON字符串一样与客户进行合作.
After that, you can operate with customers as with typical JSON string in your client.
这篇关于返回HashMap< String,Object>来自GraphQL-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!