Dragon
Dragon

Reputation: 2481

C# and JSON fields with weird characters in the name (like @)

I use Json.Net as (de)serializer. So I try to send a request with JSON body like:

 {  "Person" : {  "@personName" : "Name",     "@personAge" : 26,   } }

And the same body should be received in response. But I use "personName" and "personAge" fields for serializing the values, but I need to add "@" at the beginning of their names. As you know C# uses "@" for one can use reserved words as a variable name, so there should be some trick how to do it. Unfortunately I couldn't anything about how to do this.

I hope somebody ran at such issue and has solution for it. Thanks in advance.

Upvotes: 1

Views: 336

Answers (1)

Guillaume
Guillaume

Reputation: 13138

public class Person
{
  [JsonProperty("@personName")]
  public string PersonName { get; set; }
}

Use a JsonPropertyAttribute to specify the serialized property name.

Upvotes: 1

Related Questions