Deserialize a JSON property starting with an @ character in a C # dynamic object?

How to deserialize a Json property for a dynamic object if it starts with the @ symbol.

{ "@size": "13", "text": "some text", "Id": 483606 } 

I can get id and text properties like this.

 dynamic json = JObject.Parse(txt); string x = json.text; 
+5
source share
2 answers

Since you cannot use @ in the name of the C # token, you will need to map @size to something else, such as “SizeString” (since this is the line in your JSON above). I use the WCF data contract attribute, but you can use the equivalent JSON attribute

 ... [DataMember(Name = "@size")] public string SizeString { get; set; } ... 

Below is an example of Json string deserialization. Perhaps you can adapt to your situation or clarify your question.

 ... string j = @"{ ""@size"": ""13"", ""text"": ""some text"", ""Id"": 483606 }"; MyClass mc = Newtonsoft.Json.JsonConvert.DeserializeObject<MyClass>(j); ... [DataContract] public class MyClass { [DataMember(Name="@size")] public string SizeString { get; set; } [DataMember()] public string text { get; set; } [DataMember()] public int Id { get; set; } } 

If you do not plan to load Json into a predefined class, you can do the following ...

 var o = JObject.Parse(j); var x = o["text"]; var size = o["@size"]; 
+9
source

Assuming you are using Json.NET:

 public class MyObject { [JsonProperty("@size")] public string size { get; set; } public string text { get; set; } public int Id { get; set; } } var result = JsonConvert.DeserializeObject<MyObject>(json); 
+7
source

All Articles