I'm making a JSON body
for an elasticsearch
query.
I have this dynamic
:
var hlBodyText = new
{
bodyText = new { }
};
But there's a case in which the name must be bodyText.exact = new { }
, but obviously I'm not allowed to do it and return the error message:
Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
There's a way to make that value name with the dot char
?
Furthermore, I have to put this object inside another object, like this:
var fieldsInner = new
{
hlBodyText.bodyText
};
What could be the best way to get this result but with the property name set with the dot?
I created a class
with all my parameters beacause I thought the JsonProperty attribute
could help me.
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; }
}
then in my method i have a condition for which I have to use some params or others.
// ...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;
}
But the fieldsInner
object have the parameter names (bodyTextExact, titleExact etc...), not the JsonProperty attribute
ones.
Solved using Dictionary
, then passed it inside an 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 = {} } }
And used a RouteValueDictionary class
to read that values when elasticsearch
send his response.
RouteValueDictionary _res = new RouteValueDictionary(dynamicResponse.highlights);
if (_res["shortDescription.exact"] != null)
{
// ...
}