2

I'm about to deserialize a JSON with JavaScriptSerializer. Unfortunatly, inside the JSON, there is a variable called object.

And I cannot so write the class such as:

public class FacebookObjectDataData
{
    public FacebookObjectDataDataObject object { get; set; }

    public FacebookObjectDataData()
    {
    }
}

but I need that name for deserialize it. How can I use it?

markzzz
  • 47,390
  • 120
  • 299
  • 507
  • 1
    If you have control over the JSON output rather change the name of the variable name. If not go with the @object option – Andre Lombaard Aug 27 '13 at 13:34
  • http://stackoverflow.com/questions/91817/whats-the-use-meaning-of-the-character-in-variable-names-in-c – user2711965 Aug 27 '13 at 13:36
  • I prefer to have my variable names clear. If I see object I think of the plain Object provided in .NET. Not a custom object. I should rename it to 'data' or 'facebookData'... – RvdK Aug 27 '13 at 13:38

5 Answers5

9

You can name your field @object:

public class FacebookObjectDataData
{
    public FacebookObjectDataDataObject @object { get; set; }

    public FacebookObjectDataData()
    {
    }
}

So it will not be marked as error. You can do it with other restricted names.

For more read here http://msdn.microsoft.com/en-us/library/aa664670.aspx

Navnath Godse
  • 2,233
  • 2
  • 23
  • 32
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
4

You can use @object as variable name. The @ escapes the name so that it matches "object", it doesn't add an extra character.

See also this question.

And this post by Eric Lippert.

Community
  • 1
  • 1
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
2
public FacebookObjectDataDataObject object { get; set; }

Above won't compile since object is a reserved Keyword.

You can do something like this

public FacebookObjectDataDataObject @object { get; set; }//I don't like it personally

Or

 public FacebookObjectDataDataObject Object { get; set; }//This will work
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
2

You can use @ character to allow keyword as name of an variable

public FacebookObjectDataDataObject @object { get; set; }

also you can use DataMember attribute to change field name

[DataMember(Name = "object")]
public FacebookObjectDataDataObject facebookField { get; set; }
1

You can name it whatever you desire, just decorate it with this:

[DataMember(Name = "object")]
public FacebookObjectDataDataObject MyCoolField { get; set; }
Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89