gpt4 book ai didi

asp.net - 使用 GraphQL 和 Hot Choclate 将 IDictionary 序列化为动态 JSON

转载 作者:行者123 更新时间:2023-12-05 09:09:23 25 4
gpt4 key购买 nike

我正在使用 Web API 将 Hot Chocolate(GraphQL) 添加到现有的 ASP.Net Core 项目中,并重用 Web API 使用的模型。其中一个模型具有 IDictionary 属性,该属性使用 Web API 序列化为动态 JSON。

模型

public class Theme
{
...
public IDictionary<string, object> Styles { get; set; }
...
}

用Web API可以序列化为

{
...
styles: {
header: {
color: "#fff",
background: "rgba(255, 255, 255, 0)",
boxShadow: "", position: "fixed"},
...
},
borderRadius: "4px",
...
}
...
}

对于 Hot Chocolate,我重用了模型并在启动时添加了 GraphQL

services.AddGraphQL(sp => SchemaBuilder.New()
.AddServices(sp)
.AddQueryType(d => d.Name("Query"))
...
.AddType<Theme>()
.Create());

生成的模式变为

type Theme {
...
styles: [KeyValuePairOfStringAndObject!]
...
}

并且只能检索到 key

{
themes(...) {
edges {
node {
name
styles{
key
}
}
}
}
}

响应如下

{
"themes": {
"edges": [
{
"node": {
...
"styles": [
{
"key": "header"
},
{
"key": "borderRadius"
},
...
]
}
}
]
}
}

我想设置 Hot Chocolate 以便编写一个 GraphQL 查询来提供与 Web API 相同的动态结果。

更新

源是一个 JSON 字符串,反序列化为 Dictionary

var jsonString = "{\"header\":{\"color\":\"#fff\"},\"borderRadius\":\"4px\"}";

theme.Styles = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);

问题是生成的字典没有递归序列化为 Dictionary

最佳答案

Hot Chocolate 有一个用于动态数据结构的 AnyType。但是默认情况下 AnyType 不是从类型中隐式推断出来的。

您在这里基本上有两个选择。使用属性在您的类型上声明类型(或使用 Fluent API 执行相同操作)。

纯代码优先:

public class Theme
{
...
[GraphQLType(typeof(AnyType))]
public IDictionary<string, object> Styles { get; set; }
...
}

模式类型的代码优先:

public class ThemeType : ObjectType<Theme> 
{
protected override void Configure(IObjectTypeDescriptor<Theme> descriptor)
{
descriptor.Field(t => t.Styles).Type<AnyType>();
}
}

或者,您可以说在您的架构中所有 IDictionary<string, object>是任何类型,在这种情况下您不需要显式定义类型:

services.AddGraphQL(sp => SchemaBuilder.New()
.AddServices(sp)
.AddQueryType(d => d.Name("Query"))
...
.AddType<Theme>()
.BindClrType<IDictionary<string, object>, AnyType>()
.Create());

希望对您有所帮助。

关于asp.net - 使用 GraphQL 和 Hot Choclate 将 IDictionary<string, object> 序列化为动态 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62499255/

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