首页 > 解决方案 > 如何在 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 的属性添加到我的模型时,它可以工作,但似乎与文档不匹配。当只需要一个值时,拥有所有不同类型的值似乎不是正确和干净的代码。设计数据模型的最佳方法是什么

标签: c#jsonasp.net-web-api2

解决方案


推荐阅读