c# - 如何在 C# 中反序列化对象包含 Union 字段的 Json 对象?
问题描述
我正在尝试在 C# 中为 Google Assistant Argument 对象创建一个数据模型(https://developers.google.com/actions/reference/rest/Shared.Types/Argument)这是谷歌提供的文档片段链接。这是他们发布到我的 API 的 Json 对象的格式。
{
"name": string,
"rawText": string,
"textValue": string,
"status": {
object(Status)
},
// Union field value can be only one of the following:
"intValue": string,
"floatValue": number,
"boolValue": boolean,
"datetimeValue": {
object(DateTime)
},
"placeValue": {
object(Location)
},
"extension": {
"@type": string,
field1: ...,
...
},
"structuredValue": {
object
}
// End of list of possible types for union field value.
}
我的困惑来自“//联合字段值只能是以下之一:”。如果我不知道 Google 将向我发送什么对象,我不明白如何将对象反序列化为我的数据模型。
我试图在我的模型中列出所有可能的类型
public class Argument
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("rawText")]
public string RawText { get; set; }
[JsonProperty("textValue")]
public string TextValue { get; set; }
[JsonProperty("status")]
public Status Status { get; set; }
[JsonProperty("intValue")]
public int IntValue { get; set; }
[JsonProperty("floatValue")]
public float FloatValue { get; set; }
[JsonProperty("boolValue")]
public bool BoolValue { get; set; }
[JsonProperty("datetimeValue")]
public GoogleDateTime DateTimeValue { get; set; }
[JsonProperty("placeValue")]
public Location PlaceValue { get; set; }
[JsonProperty("extensions")]
public KeyValuePair<string, string> Extensions { get; set; }
[JsonProperty("structuredValue")]
public JObject StructuredValue { get; set; }
}
这是 Google 发布到我的 Web API 的 Json 的参数部分
"arguments": [
{
"name": "trigger_query",
"rawText": "what's happening today",
"textValue": "what's happening today"
},
{
"name": "DATEFIELD",
"rawText": "today",
"textValue": "today",
"dateValue": {
"year": 2018,
"month": 10,
"day": 23
}
}
]
谷歌应该在这个特定的用例中向我发送一个日期。当我查看上面的原始 Json 时,Google 并没有像文档建议的那样在 dateTimeValue 中发送日期,它向我发送了一个 dateValue。当我将 dateValue 的属性添加到我的模型时,它可以工作,但似乎与文档不匹配。当只需要一个值时,拥有所有不同类型的值似乎不是正确和干净的代码。设计数据模型的最佳方法是什么
解决方案
推荐阅读
- php - mysqli_stmt_bind_param():无效的对象或资源 mysqli_stmt
- css - CSS:为什么这些响应式正方形不是完全正方形的?
- sql - 对本机函数“DATE_FORMAT”的调用中的参数计数不正确
- java - 带有 Hibernate JPA 的 Java Nifi 处理器
- python - xml文本中的Python正则表达式,查找标签
- java - 使用嵌入在 Spring Boot Web 应用程序中的 Tomcat 配置 lo4j2 日志记录
- postgresql - 是否可以通过完全匹配以外的比较来查询 CKAN 数据存储?
- ms-access - 访问 - 编号字段全部默认为零
- python - Python 使用 re.sub 删除字符串后。
- javascript - iMacro 中的循环内循环