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?
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;}
}
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;}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With