我是GraphQL的新手,想知道是否有人可以帮我弄清楚以下JSON到GraphQL架构中的等价物:
[
{
"id": "1",
"name": "A",
"fldDef": [
{
"name": "f1",
"type": "str",
"opt": false
},
{
"name": "f2",
"type": "bool"
}]
},
{
"id": "2",
"name": "B",
"fldDef": [
{
"name": "f3",
"type": "str",
"opt": true
},
{
"name": "f4",
"type": "str",
"opt": true
}]
}
]
到目前为止,我设法将响应映射到下面的对象:
public class FldDef {
private String name, type;
private boolean opt;
// getters & setters
}
public class Product {
private String id, name;
private Map<String, FldDef> fldDef;
// getters & setters
}
然后我的架构如下所示,但我遇到的问题是Product
对象的一部分,我是Map
我希望获得架构适合它,但我很难获得正确的架构!
type FldDef {
name: String!
type: String!
opt: Boolean!
}
type Product {
id: String!
name: String!
fldDef: FldDef! // now here I don't know what is the syntax for representing MAP, do you know how to achieve this?
}
我得到以下异常:
Causedby:com.coxautodev.graphql.tools.TypeClassMatcher$RawClassRequiredForGraphQLMappingException: Type java.util.Map<java.lang.String, com.grapql.research.domain.FldDef> cannot be mapped to a GraphQL type! Since GraphQL-Java deals with erased types at runtime, only non-parameterized classes can represent a GraphQL type. This allows for reverse-lookup by java class in interfaces and union types.
注意:我正在使用Java生态系统(graphql-java)
答案 0 :(得分:0)
通过JSON提供模式实际上是不可能的,因为模式包含的信息远不仅仅是数据的形状。我认为最好的方法是学习GraphQL的基础知识,设计简单的模式非常简单有趣!也许从graphql.org的学习部分开始。他们有一个关于schema的部分。基本上,您可以从标量(也称为基元)和对象类型构建模式。所有类型还可以包含在非可空类型和/或列表类型中。 GraphQL是为客户设计的。理解GraphQL的最简单方法是对现有API进行一些查询。 Launchpad有很多可以使用的示例(并在您了解JavaScript时进行修改)。
答案 1 :(得分:0)
您可以尝试以下更改:
架构定义:
type FldDef {
name: String!
type: String!
opt: Boolean!
}
type Product {
id: String!
name: String!
fldDef: [FldDef]! // make it as Collection of FldDef
}
Java类:
public class FldDef {
private String name;
private String type;
private boolean opt;
// getters & setters
}
public class Product {
private String id;
private String name;
private List<FldDef> fldDef; // Change to List of FldDef
// getters & setters
}
希望它可以提供帮助。