4

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

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

This would translate into a c# class that has a field named bool. Is this possible? (My guess is no...)

I think I will need custom serialization, or maybe elastic search provides some other alternative name for bool.

Konstantin
  • 3,538
  • 2
  • 32
  • 45

3 Answers3

5

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

bool @bool = false;

I would avoid doing this in ALL circumstances where possible. It's just plain confusing.

Paul Fleming
  • 23,638
  • 8
  • 74
  • 112
2

You can set the name in a [DataMember] attribute, 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
}

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

Sklivvz
  • 29,692
  • 24
  • 116
  • 168
1

Use the DateMember attribute to specify what the serialised name is:

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

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

Community
  • 1
  • 1
Guffa
  • 666,277
  • 106
  • 705
  • 986