创建一个匿名对象,该对象必须在 Key 名称中包含点并将其放入另一个匿名对象中

Creating an anonymous object who must have the dot in Key name and put it inside another anonymous object

我正在为 elasticsearch 查询创建 JSON body

我有这个dynamic

var hlBodyText = new
{
  bodyText = new { }
};

但是有一种情况是名字必须是bodyText.exact = new { },但显然我不允许这样做并且return错误信息:

Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

有一种方法可以使用 dot char?

编辑

此外,我必须将这个对象放在另一个对象中,像这样:

var fieldsInner = new
{
  hlBodyText.bodyText
};

如果 属性 名称带有点,则获得此结果的最佳方法是什么?

编辑#2

我用我的所有参数创建了一个 class,因为我认为 JsonProperty attribute 可以帮助我。

internal class ElasticSearchHighlightsModel
{
  [JsonProperty("bodyText")]
  public object bodyText { get; set; }
  [JsonProperty("title")]
  public object title { get; set; }
  [JsonProperty("shortDescription")]
  public object shortDescription { get; set; }

  [JsonProperty("bodyText.exact")]
  public object bodyTextExact { get; set; }
  [JsonProperty("title.exact")]
  public object titleExact { get; set; }
  [JsonProperty("shortDescription.exact")]
  public object shortDescriptionExact { get; set; }
}

然后在我的方法中我有一个条件,我必须使用一些参数或其他参数。

// ...some code...
else
{
  var hlBodyText = new ElasticSearchHighlightsModel() { bodyTextExact = new { } };
  var hlTitle = new ElasticSearchHighlightsModel() { titleExact = new { } };
  var hlShortDescription = new ElasticSearchHighlightsModel() { shortDescriptionExact = new { } };

  var fieldsInner = new
  {
    hlBodyText.bodyTextExact,
    hlTitle.titleExact,
    hlShortDescription.shortDescriptionExact,
  };

  var fieldsContainer = new
  {
    pre_tags = preTags,
    post_tags = postTags,
    fields = fieldsInner,
  };
  return fieldsContainer;
}

但是 fieldsInner 对象具有参数名称(bodyTextExact、titleExact 等...),而不是 JsonProperty attribute 对象。

看来你正在寻找这个,稍后你将字典转换为json

Dictionary<string,object> obj=new Dictionary<string,object>();

obj["bodyText.exact"]=new object{};

您似乎正在创建一个匿名类型(不是 "dynamic")并希望使用在 C# 中无效的其他名称对其进行序列化。为此,您需要使用命名类型并使用 JsonProperty 属性:

internal class HlBodyText 
{
    [JsonProperty("bodyText.exact")]
    public DateTime bodyText { get; set; }
}

并创建它的一个实例:

var hlBodyText = new HlBodyText() 
{
  bodyText = new { }
};

使用Dictionary解决,然后将其传递到anonymous type obj:

IDictionary highlitsFieldsContainer = new Dictionary<string, object>();
// ... some code
highlitsFieldsContainer["bodyText.exact"] = new { };
highlitsFieldsContainer["title.exact"] = new { };
var fieldsContainer = new
{
  fields = highlitsFieldsContainer,
};

// OUTPUT: fieldsContainer = { fields = { bodyText.exact = {}, title.exact = {} } }

并在 elasticsearch 发送他的回复时使用 RouteValueDictionary class 读取该值。

RouteValueDictionary _res = new RouteValueDictionary(dynamicResponse.highlights);
if (_res["shortDescription.exact"] != null)
{ 
  // ...
}