【问题标题】:How to declare anonymous type for Json serialization, if one of the Json keys contains a dot?如果 Json 键之一包含点,如何为 Json 序列化声明匿名类型?
【发布时间】:2019-11-01 15:04:32
【问题描述】:

我正在序列化一个匿名对象以用作 HTTP 发布请求的请求消息。问题是其中一个 JSON 键的名称中包含一个点。 VS 抛出 ''invalid anonymous type member declarator'' 错误。

return JsonConvert.SerializeObject(new
{
    query = "something",
    firstname.keyword = "xyz"
});

我能做些什么来解决这个问题?

编辑:真正的 json 请求看起来像这样,所以我认为我不能使用字典:

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "firstname.keyword": ""
          }
        }
      ],
      "must_not": [ ],
      "should": [ ]
    }
  },
  "from": 0,
  "size": 10,
  "sort": [ ],
  "aggs": { }
}

【问题讨论】:

标签: c# json serialization json-deserialization


【解决方案1】:

Json 通常可以使用数组、字典和匿名对象来表示。

您的 Json 的第一部分可以生成如下:

return JsonConvert.SerializeObject(new
{
    query = new
    {
        @bool = new
        {
            must = new[]
            {
                new
                {
                    term = new Dictionary<string, object>
                    {
                        ["firstname.keyword"] = string.Empty,
                    }
                }
            }
        }
    }
});

【讨论】:

    猜你喜欢
    • 2010-09-24
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    相关资源
    最近更新 更多