返回 HashMap<String, Object>来自 GraphQL-Java [英] Return HashMap&lt;String, Object&gt; from GraphQL-Java

查看:47
本文介绍了返回 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆