Is it possible to have a field named bool in C #?

I am sitting playing with elastic search with C # and I wanted to create a query using an anonymous type in C # serialized for JSON. But I ran into a problem as I need JSON that looks like this:

{"bool": {<unimportant for question>}} 

This translates to a C # class that has a field called bool. Is it possible? (My guess is no ...)

I think I will need custom serialization, or maybe elastic search will give another alternative name for bool.

+4
source share
3 answers

If you want to name the variables the same as keywords, you can prefix them with @ .

bool @bool = false;

I would avoid doing this wherever possible. This is just confused.

+5
source

You can set the name in the [DataMember] , but you need to use real classes (not anonymous).

 using System; using System.Collections; using System.IO; using System.Runtime.Serialization; using System.Xml; // You must apply a DataContractAttribute or SerializableAttribute // to a class to have it serialized by the DataContractSerializer. [DataContract()] class Enterprise : IExtensibleDataObject { [DataMember(Name = "bool")] public bool CaptainKirk {get; set;} // more stuff here } 

Additional information: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx

+2
source

Use the DateMember attribute to indicate what a serialized name is:

 [DataMember(Name = "bool")] public string MyBoolean { get; set; } 

See also: JavaScriptSerializer.Deserialize - how to change field names

+1
source

Source: https://habr.com/ru/post/1441142/


All Articles