user1429899 user1429899 - 1 year ago 105
C# Question

Deserialize JSON property starting with @ symbol into C# dynamic object?

How to deserialize Json property to dynamic object if it starts with @ 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;

Les Les
Answer Source

Since you can't use @ in a C# token name, you would need to map the @size to something else, like "SizeString" (since it is a string in your JSON above). I use the WCF data contract attribute, but you could use the equivalent JSON attribute

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

Here is an example of how to deserialize the Json string. Maybe 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);

public class MyClass
    public string SizeString { get; set; }
    public string text { get; set; }
    public int Id { get; set; }

If you don't plan loading the Json into a predefined class, you can do the following...

var o = JObject.Parse(j);
var x = o["text"];
var size = o["@size"];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download