Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - how to use invalid characters in a variable name

Tags:

json

c#

In C#, I'm building a class (simplified here for discussion purposes) that eventually will be serialized into some externally defined JSON:

    { 
    "$schema": "http://example.com/person.json",
    "name": "John",
    "age": 86
    }

In my code I would have something like:

public class Person
{
    public const string $schema= @"http://example.com/person.json";
    public string name {get;set; }
    public int age {get; set;}
}

...

 Person person = new Person();
 person.name = "John";
 person.age = 88;

 JavaScriptSerializer serializer = new JavaScriptSerializer();
 string json = serializer.Serialize(person);

In my code above the $schema is causing an "Unexpected character '$' error. Is there a workaround?

like image 798
Damon Brodie Avatar asked Jan 18 '16 22:01

Damon Brodie


2 Answers

If using JSON.NET, you can use the JsonProperty attribute:

public class Person {
    [JsonProperty(PropertyName = "$schema")]
    public string schema {get; set;} = @"lsjdhflsjkdf";

    public string name {get;set;}
}
like image 58
Sam Axe Avatar answered Oct 29 '22 07:10

Sam Axe


Provide the attribute [DataContract] to your Person class.

Also, did you mean to make schema const?

[DataContract]
public class Person
{
    [DataMember(Name = "$schema")]
    public string schema { get; set; }
    public string name { get; set; }
    public int age {get; set;}
}
like image 36
jacob Avatar answered Oct 29 '22 06:10

jacob